Tutorial :Learning Try-Catch


I'm a Java beginner so please bear with me

static int load = 100;  static int greet;    public void loadDeduct(int cLoad, int c){      int balance;      balance = cLoad - 7;      System.out.println("Your balance: " + balance);  }    public void loadDeduct(int tLoad){      int balance;      balance = tLoad - 1;      System.out.println("Your balance is: " + balance);  }    public static void main (String [] args){      int choice;      Scanner scan = new Scanner(System.in);        System.out.println("I'm a cellphone, what do you want to do?");      System.out.println("Press 1 to send SMS / Press 2 to Call");        choice = scan.nextInt();        CellphoneLoad N95 = new CellphoneLoad();        if (choice == 1){          N95.loadDeduct(load);      }else if (choice == 2){          N95.loadDeduct(load, greet);      }else{          System.out.println("Invalid Option!!!");      }  

How do I implement the exception handling with this program? I'm not quite sure how to use the catch block as we weren't taught yet about the whole exceptions thing. It was just an exercise we were asked to do. I want to replace the if else statements with a try-catch blocks... is that possible?


One important principle to consider with exceptions in Java is that there are two types: 1. Runtime 2. Typed/explicit (for lack of a better word)

Runtime exceptions should be thrown when there is a programming error and generally they should not be caught unless you are catching at the top level to report an error.

Typed/Explicit exceptions are decorated on method calls and should be there so the caller can take some action on them.

In the case of the code above, there isn't really a place that feels like it should use exception handling.

And as Patrick pointed out, you don't generally want to use exceptions for flow control.


It is not ideal to use Exceptions for flow control. From your code it is not clear what Exceptions might be thrown. Maybe you can elaborate a bit more.


The Scanner.nextInt() method can throw a few exceptions. The linked page of the API Specifications lists out the three exceptions which can be thrown.

For example, if a non-integer value is entered, such as "one" instead of 1, an InputMismatchException can be thrown.

In general, a try-catch is used to catch exceptions, as illustrated in the following code:

try  {      Integer.parseInt("one");      // Statement that can cause an exception.  }  catch (NumberFormatException e)   // Specify which exception to catch.  {      // Code to handle the NumberFormatException.  }  

More information about exceptions can be found in Lessons: Exceptions of The Java Tutorials. In particular, the Catching and Handling Exceptions section may be useful.


Adding exceptions in this piece of code does not add much value. What I can think of is something like this:

public static void main (String [] args){    .....    try{   handleUserChoice(choice);//new method  }  catch(InvalidChoiceException e){   System.out.println("Invalid Option!!!");  }  }  


The only part of your code that might possibly throw an exception is the call to:


According to the JavaDocs, this can throw the following possible exceptions:

  • InputMismatchException (if the next token does not match the Integer regular expression, or is out of range)
  • NoSuchElementException (if input is exhausted)
  • IllegalStateException (if this scanner is closed)

So if you wanted your code to account for the possibilities of these exceptions being thrown, you should re-write it like so:

try {      choice = scan.nextInt();  }   catch (InputMismatchException e) {    System.out.println(e.getMessage());  }  catch (NoSuchElementException e) {    System.out.println(e.getMessage());  }  catch (IllegalStateException e) {    System.out.println(e.getMessage());  }  

Generally, you want your "catch" blocks to start out specific or very likely to happen to less likely / more general in nature.

You can additionally "throw" the exceptions so that whatever method the exception occurs in doesn't handle it-- the method which called that exception-causing method would have to handle it (or throw it again, etc, until it gets to the Java runtime).

In the event it's the "if" statement you wish to replace, I'd recommend the "switch" statement:

switch (choice) {      case 1:  N95.loadDeduct(load);               break;      case 2:  N95.loadDeduct(load, greet);               break;      default: System.out.println("Invalid Option!!!");  }  


I don't see any reason to use exceptions instead of the if-else block. you could try using a switch statement, it'd look better.

you should use exceptions to handle errors that might occur inside the methods loadDeduct. then you would surround the lines calling N95.loadDeduct with a try-catch block, to write what would happen if loadDeduct went wrong.


It's really pretty simple. First identify where you want an exceptioon. There can be exceptinos thrown by library code or you can throw your own. Then use a try .. catch to handle it. Here's a simple "hello, world" ish example:

public class TryTry {        public void doIt() throws Exception {         System.err.println("In the doIt method.");         throw new Exception("Hello there!");      }        public static void main(String[] argv){         TryTry t = new TryTry();         // here we'll catch it.         try {             System.err.println("About to call doIt().");            t.doIt();         } catch (Exception e) {  // e now has your exception object            System.err.println("In the exception handler.");            System.err.println("Exception says: "+ e);         }      }  }  

The effect of throw is to construct that exception object and send it up the stack until it's caught. To catch it, you surround the code that might throw it with tr { ... }, and handle the exception with catch.

Here's the results:

    javac TryTry.java && java TryTry  About to call doIt().  In the doIt method.  In the exception handler.  Exception says: java.lang.Exception: Hello there!  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »