Java Exceptions Exceptions Often in computing, operations cannot properly execute because some sort of error has occurred. Some examples: – A program tries to open a file which does not exist. – A disk drive fails when a program is trying to read from it. – An attempt is made to divide by zero. Traditional Ways An exception is an indication that something went wrong in a program. Traditionaly, error checking is tangled with the code that provides normal functionality. … … if(num != 0) { result = 100/num; } else { //print error //get new value //do more stuff } … … Java Exceptions The error checking and recovery breaks up the flow of normal processing. Removing error checking and recovery from the normal flow of a program will: – Make code easier to read – Make code easier to write Exception handling allows programmers to handle exceptional cases outside the normal flow of control. Addition Example We saw earlier that our Addition class did not catch possible exceptions. – Invoking Integer.parseInt(String) resulted in a NumberFormatException if the string provided did not represent a valid integer. ... Catching Exception (Easy way) try { number1 = Integer.parseInt( firstNumber ); number2 = Integer.parseInt( secondNumber ); } catch (NumberFormatException e) { JOptionPane.showMessageDialog(null,“Input ERROR”); System.exit(0); } sum = number1 + number2; JOptionPane.showMessageDialog( null, "The sum is " + sum, "Results", JOptionPane.PLAIN_MESSAGE ); System.exit( 0 ); // terminate the program ... Catching Exception (Better way) ... boolean inputOK = false; while (!inputOK) { inputOK = true; firstNumber = JOptionPane.showInputDialog("Enter first integer" ); try { number1 = Integer.parseInt( firstNumber ); } catch (NumberFormatException e) { JOptionPane.showMessageDialog(null, “Input ERROR!”); inputOK = false; } } … < same for secondNumber > … Exception Hierarchy Java Errors In Java the Error class defines serious errors that the programmer should not even attempt to recover from. Typical Errors are: – Virtual Machine Errors – Out of memory – Stack overflow – Windowing Error Java Exceptions In Java the Exception class defines mild error conditions that your programs might encounter. Rather than blindly terminating the program, you can write code to handle your exceptions and continue executing the program. RunTimeException Other type of Exceptions (We call them Non RunTimeException) Typical exceptions – The file you are trying to open doesn’t exist – The network connection is disrupted – The user entered invalid data – The numeric values you are manipulating are out of the prescribed range – Trying to use an uninitialized reference – Going outside the bounds of an array try/catch try/catch blocks are used to catch and handle exceptions try { … //normal flow of program } catch(Exceptiontype reference) { … //exception handler code } try/catch If an exception occurs within a try block, all catch blocks will be searched for a matching exception type. The keyword throw is used to throw an exception throw new ExceptionType(); The exception can be thrown from within a method and be handled by the caller. try/catch Catch blocks specify different types (All derived from ‘Throwable’) of exceptions. If an exception is caught, the flow of control will enter the catch block. Once the block is done executing, flow of control will pick up after the last catch block try/catch If an exception is not caught locally, the next enclosing try/catch block will be tested. The order of enclosing try/catch blocks will follow the call stack. finally The finally statement defines a block of code that always executes regardless of whether an exception was caught. try {//protected code startFaucet(); waterLawn(); } catch(Exception e) { //handle exception } finally { stopFaucet(); } What need to be done for the three types of exceptions There are two types of exceptions in Java: – RuntimeException- indicates a design or implementation problem that occurs because the programmer made a mistake. This should never happen if the program is running properly. Not required by compiler to be handled. Programmer is encouraged to handle though – Non-RuntimeException- indicates difficulty at runtime. File not present, user enters invalid data. must be checked, either handled or propagate Common Exceptions – ArithmeticException – NullPointerException – NegativeArraySizeException – ArrayIndexOutOfBoundsException – SecurityException – IOException Handle or Declare Rule Java requires that if an Non RunTimeException occurs while a method is executing the caller must determine what action is to be taken. There are two things that can be done by the caller – Enclose the method call in a try/catch block – Indicate that the calling method will not handle the exception Handle or Declare Rule To indicate that the calling method will not handle the exception use the keyword throws in the method definition. public void foo() throws ExceptionType This indicates that foo will not handle the exception, but whoever called foo will. This rule only applies for exceptions derived from Exception but not derived from RuntimeException Try, Catch, Finally try tryblock catch (exception_type identifier) catchblock catch (exception_type identifier) catchblock ......... // 0 or more of these finally // 0 or 1 of these finallyblock Try, Catch and Finally Execute tryblock of statements until either an exception is thrown or the block finishes successfully. If an exception is thrown, the catch clauses are examined in order, to find one for an exception of the thrown class or one of the thrown classes superclasses. If none are found, propagate the exception to a surrounding try block, and if needed to the calling method. The finally block is always executed, even if no exceptions are thrown. Another try/catch example public static String readString() { int ch; String r = ""; boolean done = false; while (!done) { try { ch = System.in.read(); if (ch < 0 || (char)ch == `\n’) done = true; else r = r + (char) ch; } catch(IOException e) { done = true; } }; return r; } /* try block */ /* catch clause */ /* handler code */ Propagating an Exception if you call a method that throws a checked exception, you must either handle it or propagate it. propagate an Exception by adding a throw clause in the method header Example public static String readString() throws IOException { int ch; String r =""; boolean done = false; while (!done) { ch = System.in.read(); if (ch < 0 || (char)ch == `\n’) done = true; else r = r + (char) ch; }; return r; } Finally Example public boolean searchFor(String file, String word) throws StreamException { try { input = new Stream(file); while (!input.eof()) if ((input.next()).equals(word)) return true; //word found return false; //word not found } finally { //finally block is executed whether or not try throws an exception. if (input != null) input.close(); }} Exception not caught If an exception occurs and is not caught (in a non-graphical application) Java will terminate the program, and display a message and a stack trace to the console. printStackTrace() getMessage() main() { fie(); } fie() { foo(); } foo() { int i=1; int j=0; i = i/j; } Divide by 0 exception thrown. Runtime looks for an enclosing try..catch statement in foo(). Runtime then looks for enclosing try... catch statement in method which called foo(): fie(). Runtime than looks for enclosing try... catch statement in method which called fie(): main(). If exception not caught when it leaves your program, the default catch is used which returns an error message. Throwing Exception Exceptions are thrown (signaled) when – you make a programming error (system throws an exception implicitly.) – you call a method that throws an exception. – you detect an error and throw an exception explicitly. – an internal error occurs in Java. (Error Class) Example 1 class ImplicitThrow { public static main(String[ ] args) { int i = 1, j=0, k; k= i/j; System.out.println("k is " + k); }} Throws an ArithmeticException Unchecked exceptions need not be declared Example 2 class MethodThrows { public Image loadImage(String source) throws MalformedURLException, IOException { URL url = new URL(source); InputStream in = url.openStream() } } Throws MalformedURLException, IOException Method Must declare checked exceptions Explicitly Throw an Exception Find an appropriate exception class from the API (or define your own by subclassing Exception) create an object of that class throw it Thrown exceptions dealt with by calling method. This declaration forces calling method to catch exception or propagate it. Rethrow? Example 3 String readInput (BufferedReader in) throws EOFException /* throw clause */ { . . . while (. . .) { if (ch == -1) /* EOF encountered */ { if (n < len) throw new EOFException(); } . . . } return s; } Another Explicit throw class MyExceptionThrow { public String readLines(DataInputStream in) throws FewLinesException, IOException { int length = 1024, n = 0; String line; line=in.readline(); while (line!= null) { n++; line = in.readLine(); } if (n < length) throw new FewLinesException(); // Throw user defined exception else return "Enough lines read in!"; }} Define your own Exception types Exception classes can have constructors, methods, polymorphic methods, etc… class FewLinesException extends IOException { public FewLinesException() { } public FewLinesException(String msg) { super(msg); } } Handling Checked Exceptions If you invoke a method that lists a checked exception in its throws clause, you must either: – Catch the exception and handle it. – Declare the exception in your methods throws clause and let the exception pass through your method by doing nothing Must deal with thrown exceptions import java.net.*; class Except1 { static URL imageURL; public static URL getURL(String urlstr) { return new URL(urlstr); } public static void main(String[] args) { imageURL = getURL("haha"); } } URL.URL() declared to throw MalformedURLException Except1.java:7: Exception java.net.MalformedURLException must be caught, or it must be declared in the throws clause of this RuntimeException and Non- RuntimeException Non-RuntimeException – must be caught – or declared in the throws clause of any method that can throw them. Subclasses of RuntimeException, Error – unchecked exceptions (not required to explicitly catch) Still Complain import java.net.*; class Except1 { static URL imageURL; public static URL getURL(String urlstr) throws MalformedURLException{ return new URL(urlstr); } public static void main(String[] args) { imageURL = getURL("haha"); } } No compile complain import java.net.*; class Except1 { static URL imageURL; public static URL getURL(String urlstr) throws MalformedURLException{ return new URL(urlstr); } public static void main(String[] args) throws MalformedURLException{ imageURL = getURL("haha"); } } Run-time complain Inheritance and Exception Handling It is good practice to define your own exception types. Inheritance can be used. It is good practice to define your own exception types. Catch exception object of superclass type allows for polymorphic processing of related errors Java Exceptions and Inheritance Java Exceptions and Inheritance