Logout

Home Topic 4

Exception Handling - Throws & Try/Catch

"Exceptions"

Exceptions are errors that can happen in the middle of running Java code that we as programmers don't have full control over. That's why they are"exceptional"; they are thngs we can't 100% anticipate happening, and/or things that we cannot 100% prevent them from happening. A perfect example of this is input/output errors caused by electromagnetic interference in the wires going from a keyboard to a computer, for example. And the problem with all such errors, is if left unhandled, the program will simply freeze when encountering them.

(You'll note that there are two other categories of errors which we as programmers do have under our control: syntax errors (spelling/grammar mistakes), and semantic errors (errors in the logic of our code).)

Understanding all of this is not actually required as part of the IB curriculum, but the thing is, minimal handling of potential exceptions (i.e. errors) is required by Java for various situations. Fortunately it is not that big a deal to use simple try/catch blocks or include throwable statements.

The Exception Classes of Java

There is a libaray of many pre-build Java classes availabie to us, which specialize in knowing how to handle certain kinds of exceptions. They all stem from the super class called Exception. Exception classes which are commonly used include IOException, ArrayIndexOutOfBoundsException, and ArithmeticException.

Using "throws"

With throws, you can simply stipulate that a particular method will throw a particular kind of exception if that kind of error is encountered. And that's it; you don't have to do anything else. If an error of that kind happens, the program does not freeze; though it will cease running that part of the program.

Using "try/catch" blocks

With a try/catch block, the idea is that a try block will be "tried", and if in the middle trying that block of code, an exception (i.e. a problem) is encountered, then the control of the program is passed to the catch block, rather than having the program simply freeze. So the catch block can do some sort of printline or OptionPane which indicates what sort of problem there must have been.

 

Example # 1a - A problem; user input being attempted, and this is a situation for which Java requires exception handling. But none implemented at this point.


12  public class ForExceptionsNotes {
13  
14      public static void main(String[] args) {
15              BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
16              System.out.println("What is your name?");
17              String name = br.readLine(); //<------------ ERROR ERROR ERROR
18              System.out.println("Welcome to this program " + name);
19      }
20  
21  }

 

Example # 1b - The simplest, generic way of handling all exceptions:

simply "throw" an object of the Exception class in the method header.


12  public class ForExceptionsNotes {
13  
14      public static void main(String[] args)  throws Exception { //<-------------- HERE IS THE SIMPLEST SOLUTION
15              BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
16              System.out.println("What is your name?");
17              String name = br.readLine();
18              System.out.println("Welcome to this program " + name);
19      }
20  
21  }

 

Example # 1c - A bit better way of handling a specific exception:

throw the specific exception which could happen; in this case, not just the generic Exception, but IOException, since it's input we are attempting.


12  public class ForExceptionsNotes {
13  
14      public static void main(String[] args)  throws IOException { //<--------- A BIT BETTER; A specific exception thrown
15              BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
16              System.out.println("What is your name?");
17              String name = br.readLine();
18              System.out.println("Welcome to this program " + name);
19      }
20  
21  }

 

Example # 1d - The best way of handling a specifc exception - at least in the testing stages of development:

try the code that may have the problem, and catch the specific kind of exception you anticipate.


12  public class ForExceptionsNotes {
13  
14      public static void main(String[] args){
15             try{
16                     BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
17                     System.out.println("What is your name?");
18                     String name = br.readLine(); 
19                     System.out.println("Welcome to this program " + name);
20             }
21             catch(IOException ex){                    //<--------------------------BEST SOLUTION: try and specific exception caught
22                     System.out.println("There was some kind of input/output error.");
23                     System.out.println("Here is the message "
24                         + "delivered by the error " + ex.getMessage());
25             }
26      }
27  
28  }

 

Example # 1e - Catching possible multiple exceptions:


12   public class ForExceptionsNotes {
13        public static void main(String[] args)  {
14           try {
15               BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
16               System.out.println("What is the first number?");
17               double num1 = Double.parseDouble(br.readLine());
18               System.out.println("What is the second number?");
19               double num2 = Double.parseDouble(br.readLine());
20               double numberOfNumbers = 2;
21               double average = (num1 + num2) / numberOfNumbers;
22               System.out.println("The average of the two numbers typed in is: " + average);
23           }catch(IOException ex){    //<---------------------------------------------------------------- EXCEPTION # 1
24               System.out.println("There was an input/output problem.");
25               System.out.println("Here is the message "
26                       + "sent back by the error: " + ex.getMessage());
27           } catch (NumberFormatException ex) {   //<----------------------------------------------- EXCEPTION # 2
28               System.out.println("There must have been an error in your input."
29                       + "You probably typed in letters instead of numbers.");
30               System.out.println("Here is the message returned by the error: " + ex.getMessage() 
31                       + ". Please run this program again.");          
32           }
33       }
34   }

---------------------------------------------------------------------------------------------------

Example # 2 - Another example: IndexOutOfBounds.

/Users/adelaide/Public/Netbeans - All JSR Projects/String Playing Around/src/TwoDArrayReview.java
 1 
 2 import java.io.BufferedReader;
 3 import java.io.InputStreamReader;
 4 import java.io.IOException;
 5 
 6 
 7 public class TwoDArrayReview {
 8 
 9     public static void main(String[] args)  {
10 
11         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
12         try {
13             String[][] robotsArray = {{"Prague", "Pink Pony Prnicess"}, {"Budapest", "Bucaneers"}, {"Warsaw", "Warriors"}, {"Bucharest", "Vampires"}};
14             //Note that the use of a 2D array here does not really affect any of the exception handling.
15             
16             System.out.println("Which team would you like to get the name of (type in a number)");
17             int row = Integer.parseInt(br.readLine());
18 
19 
20             if (row > robotsArray.length - 1) {
21                 throw new ArrayIndexOutOfBoundsException();
22                 //So this is where we throw a particular kind of exception which would occur with the condition above.
23             } else {
24                 System.out.println("The name of the team is: " + robotsArray[row][1]);
25             }
26         } catch (ArrayIndexOutOfBoundsException e) {
27             System.out.println("We had an indexoutofboundserror as proven by the following message thrown in the exception:\n"
28                     + e.getMessage());
29         } catch (IOException e) {
30             System.out.println(e.getMessage());
31         }
32         System.out.println("and now for something else");
33 
34     }
35 }

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Example # 2B - Alternative approach using an if/else conditional block:

a new ArrayIndexOutOfBoundsException thrown within a conditional block, but not caught. This will prevent the program from freezing, but not give any feedback via a catch block.

 1   
 2   import java.io.BufferedReader;
 3   import java.io.InputStreamReader;
 4   import java.io.IOException;
 5   
 6   
 7   public class TwoDArrayReview {
 8   
 9       public static void main(String[] args)  {
10          BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
11          try {
12              String[][] robotsArray = {{"Prague", "Pink Pony Princess"}, {"Budapest", "Bucaneers"}, {"Warsaw", "Warriors"}, {"Bucharest", "Vampires"}};
13              //Note that the use of a 2D array here does not really affect any of the exception handling.
14              
15              System.out.println("Which team would you like to get the name of (type in a number)");
16              int row = Integer.parseInt(br.readLine());
17  
18  
19              if (row > robotsArray.length - 1) {
20                   new ArrayIndexOutOfBoundsException();
21                  //So this is where we throw a particular kind of exception which would occur with the condition above.
22              } else {
23                  System.out.println("The name of the team is: " + robotsArray[row][1]);
24              }
25          //} catch (ArrayIndexOutOfBoundsException e) {
26              //System.out.println("We had an indexoutofboundserror as proven by the following message thrown in the exception:\n"
27                      //+ e.getMessage());
28          } 
29          catch (IOException e) {
30              System.out.println(e.getMessage());
31          }
32          System.out.println("and now for something else");
33  
34      }