Unformatted text preview:

Chapter 8Exception HandlingCS 180Sunil PrabhakarDepartment of Computer Science Purdue UniversityClarificationsAuto cast from char to String does not happen. Cast between int and char happens automatically.Class is a data type. It is possible to get the class of any object. Part of Reflection in JavaAdvanced topic 23When things go wrongGood programs should be robust -- I.e., they should be able to handle exceptional situations.What happens if we are trying to input an integer value and the user enters “ten”, or “3.45”?A good program should tell the user to re-enter a valid integer.So far, a situation such as this would result in the termination of our program when we execute Integer.parseInt() on this invalid string.How do we prevent this?4Handling errorsOne idea is to use if -then style tests whenever we expect that an error may arise.This is the style in C -- return values can signal the existence of an error.But this is clumsy, and inelegant. In Java, the exception handling mechanism is used instead.Unexpected (or unusual) cases are handled by a special type of control flow.5ExceptionsAn exception is used to indicate that something unusual (that prevents regular processing) has occurred.When an exception occurs, or is thrown, an Exception object is created, and the normal sequence of flow is terminated. An exception handling mechanism is invoked which is responsible for handling or catching the thrown exception.6Uncaught ExceptionsWhen an exception is thrown, and the program does not specify how to catch it, it causes the program to terminate:import javax.swing.*;public class Test{public static void main(String[] args){String inputStr;int i;inputStr = JOptionPane.showInputDialog(null, “Enter Deposit Amount”);i = Integer.parseInt(inputStr);}}Catching an exception7String inputStr;int i;inputStr = JOptionPane.showInputDialog(null, “Enter an integer”);try{i = Integer.parseInt(inputStr);} catch (Exception e){System.out.println(“Invalid integer”);}Exception control-flow8. . .try{ . . . stmt; . . .} catch (Exception e){ . . .}. . .. . .try{ . . . stmt; . . .} catch (Exception e){ . . .}. . . Exception is thrown when executing this statement.No exception Exception thrown9Exception objectAn exception is thrown by creating an Exception object.The exception object is passed to the catch block as a parameter.It contains details about the actual exception that was thrown.try { . . .} catch (Exception e){ . . .}e is a catch block parameter corresponding to the exception object.10Exception objectThe exception object contains details about the exception.The getMessage() method simply returns a string of text that describes the exception.The printStackTrace() method gives us the order (and line numbers) in which methods had been called when the exception took place. In reverse order of the calls The last method call is listed first, main is last.11The Exception HierarchyExceptionNullPointerExceptionArithmeticExceptionIllegalArgumentExceptionNumberFormatExceptionRunTimeExceptionIOExceptionMany more.See Java APISQLException12Multiple catch BlocksIf more than one type of exception can take place, we may want to handle each one differently.A single try-catch statement can include multiple catch blocks, one for each type of exception.Only the first matching catch block is executed.Matching is based on the class of the exception.Make sure to list classes lower in the hierarchy before listing classes higher up.13Multiple catch BlocksStudent s;try { . . . i = Integer.parseInt(inputStr); . . . s.getName();} catch (NumberFormatException e){ . . . // code to handle NumberFormatExceptions.} catch (NullPointerException e){ . . . // code to handle NullPointerExceptions.} catch (Exception e){ . . . // code to handle all other exceptions.}14Terminating a programIt is possible to terminate a program at any point in its execution (maybe because a very serious error has occurred).This is achieved by calling System.exit(0)This call takes any integer value as a parameter.The program is immediately terminated.15The finally BlockThere are situations where we need to take certain actions regardless of whether an exception is thrown or not.We place statements that must be executed regardless of exceptions, in the finally block.Commonly used to perform cleanup (e.g., closing disconnecting from a database, or closing a network connection)Exception control-flow16. . .try{ . . . stmt; . . .} catch (Exception e){ . . .}finally { . . .}. . .. . .try{ . . . stmt; . . .} catch (Exception e){ . . .}finally { . . .}. . . Exception is thrown when executing this statement.No exception Exception thrownfinally block is always executed.17Salient pointsIf multiple catch blocks are defined they are tested in order -- only the first that matches the thrown exception gets executed.List them from more specific to general.CAUTION: if A is a subclass of B, then an exception of class A is also an exception of class B!Even if there is a return from the try or catch blocks, the finally block is executed before returning!If no matching catch block is found for an exception, the finally block gets executed18Caution: order of catch blocksStudent s;try { . . . i = Integer.parseInt(inputStr); . . . s.getName();} catch (Exception e){ . . . // code to handle general exceptions.} catch (NullPointerException e){ . . . // code to handle NullPointerExceptions.} catch (NumberFormatException e){ . . . // code to handle NumberFormatExceptions.} Will never get executed!Propagating exceptionsIf an exception occurs and there is no matching catch block, then the exception is propagated.control passes to the callerif the caller has no matching catch block, the same happenseventually, if the main method does not handle the exception, the runtime system handles it.19Exception handling20public static void main(String[] args){...a.methodA();...}public void methodA(){try{methodB();} catch (NumberFormatException e){. . .}. . .}public void methodB(){stmt;}NumberFormatException is thrown when executing this statement.Exception is propagatedException is handled.Exception handling21public static void main(String[] args){...a.methodA();...}public void methodA(){try{methodB();} catch (NumberFormatException e){. . .}. . .}public void methodB(){stmt;}NullPointerException is thrown when


View Full Document

Purdue CS 18000 - Exception Handling

Download Exception Handling
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Exception Handling and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Exception Handling 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?