90 likes | 104 Views
Learn about exception handling in Java, including the types of exceptions, using try-catch blocks, and an example implementation.
E N D
Exception Handling Contents • Many classes in the Java standard library throw exceptions • “throws clause” (or try-catch block) is needed in the function header of any function that contains a message to a library method that throws an exception • Error message if “throws clause” or try-catch blocks are missing • Types of exceptions • Try-catch blocks • The Exception hierarchy • An example using try-catch blocks • The anatomy of an exception
Exception Handling Most of Java’s I/O classes (and many others) throw exceptions. For example: Consider a function with a message readLine( ) directed to a BufferedInputReader object import java.io.*; //needed for streams and IOException public class ExceptionalExample { publicstaticvoid main(String [ ] args) { throws IOException InputStreamReader isr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(isr); System.out.println(“Enter a number”); String str = br.readLine( ); The statement “throws IOException” is required when using readLine( ). It must be included in the header of any function in which readLine( ) appears. Provide stream readers to convert characters (read as integers) into a string, then prompt the user for a number. Read the supplied number (as a String) from the keyboard.
ExceptionalExample.java:10: unreported exception java.io.IOException; must be caught or declared to be thrown String str = readLine( ); 1 error c:\javacode> ^ Exception Handling If we fail to include the “throws IOException” clause in the main function header we will see the following error reported when we compile the program ExceptionalExample: c:\javacode>javac ExceptionalExample.java Method readLine( ) throws an IOException. Any function that uses it must either throw the same exception (and pass the buck to the operating system to handle the exception) or catch the exception and provide its own error handling methodology. In the previous example we chose the first strategy.
Exception Handling Types of exceptions Checked exceptions – inability to acquire system resources (such as insufficient memory, file does not exist) Java checks at compile time that some mechanism is explicitly in place to receive and process an exception object that may be created during runtime due to one of these exceptions occurring. Unchecked exceptions – exceptions that occur because of the user entering bad data, or failing to enter data at all. Unchecked exceptions can be avoided by writing more robust code that protects against bad input values. Java does not check at compile time to ensure that there is a mechanism in place to handle such errors. It is often preferred to use Java’s exception handling capabilities to handle bad user input rather than trying to avoid such circumstances by providing user-input validation in the code.
Exception Handling The try / catch blocks try { //statements – one of which is capable of throwing an exception } catch (ExceptionTypeName objName) { //one or more statements to execute if this exception occurs } finally { //statements to be executed whether or not exception occurs } Encapsulate statement or statements that can throw an exception in a try block. One or more catch blocks must immediately follow a try block to provide error handling routines for any exceptions that occur while executing the statements in the try block. Each catch block specifies the type of exception that it handles in a parameter list. An optional finally block can be added at the end of the catch blocks to provide a set of statements that are always executed whether or not an exception occurs.
Exception IOException DataFormatException RunTimeException NumberFormatException EOFException FileNotFoundException InterruptedIOException Exception Handling The exception hierarchy (partial) All exceptions inherit from a base class Exception Common Exception sub classes include: IOException can be decomposed into specific classes of I/O errors NumberFormatException is a subclass of DataFormatException
Will throw NumberFormatException if str cannot be converted to a double. Exception Handling Example Consider implementing the BufferReader readLine( ) example with try-catch clocks. import java.io.* public class ExceptionalExample { publicstaticvoid main(String [ ] args) //no throws clause used here { InputStreamReader isr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(isr); System.out.println(“Enter a number”); try { String str = br.readLine( ); double num = Double.parseDouble(str); } try block encapsulates the readLine( ) method and the conversion from String to double.
catch the IOException object thrown by readLine( ) Exception Handling Example (continued) //add the catch blocks catch (IOException ioe) { //print a message to the screen System.out.println(ioe.toString( )); } catch (Exception e) { //catch any other exception and print a message to the screen System.out.println(e.toString( )); } finally { System.exit(0); } Note! ioe is a handle (reference) to an IOException object thrown by readLine( ) Note! toString( ) is a method that all Classes inherit (implicitly). In the finally clause we ensure that the program terminates properly – exit(0) signifies normal termination. Since both catch blocks have the same implementation in this example, there is no need to single out IOException in a separate block.
ExceptionalExample br:BufferedReader IOException Exception Handling The anatomy of an exception In the main( ) function of ExceptionalExample a BufferedReader object called br is created and attatcher to isr. An error occurs while attempting to read from the keyboard. An IOException object is created. br.readLine( ) is called inside of a try block in function main( ) The IOException is passed to the catch block in function main( ) Message is sent to object referenced by ioe to execute its toString( ) method (inherited from implicit base class Object) try { String str =br.readLine( ); } catch (IOException ioe){ System.out.println(ioe.toString()); } new readLine( ) {..} toString( ) {…}