OBJECT ORIENTED PROGRAMMING Course 6 Loredana STANCIU loredana.stanciu@upt.ro Room B616
Exceptions An event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions When an error occurs within a method exception object throwing an exception The runtime system attempts to find something to handle it call stack
Exceptions Exception handler block of code that can handle the exception The exception handler chosen is said to catch the exception If no exception handle found the program terminates
Exceptions
The Catch or Specify Requirement The code that might throw certain exceptions must be enclosed by: A try statement that catches the exception A method that specifies that it can throw the exception must provide a throws clause Code that fails to honor the Catch or Specify Requirement will not compile.
The Three Kinds of Exceptions 1) the checked exception exceptional conditions that a well-written application should anticipate and recover from Exp: try to open for reading a file but the file does not exist java.io.filenotfoundexce ption catch this exception and notify the user of the mistake
The Three Kinds of Exceptions 2) the error conditions that are external to the application, and that the application usually cannot anticipate or recover from indicated by Error and its subclasses Exp: an application successfully opens a file for input, but is unable to read the file java.io.ioerror
The Three Kinds of Exceptions 3) the runtime exception are exceptional conditions that are internal to the application, and that the application usually cannot anticipate or recover from indicated by RuntimeException and its subclasses Exp: If a logic error causes a null to be passed to the constructor NullPointerException
Catching and Handling Exceptions //Note: This class won't compile by design! import java.io.*; import java.util.list; import java.util.arraylist; public class ListOfNumbers { private List<Integer> list; private static final int SIZE = 10; public ListOfNumbers () { list = new ArrayList<Integer>(SIZE); for (int i = 0; i < SIZE; i++) list.add(new Integer(i));
Catching and Handling Exceptions public void writelist() { PrintWriter out = new PrintWriter( new FileWriter("OutFile.txt")); // (1) for (int i = 0; i < SIZE; i++) out.println("value at: " + i + " = " + list.get(i)); // (2) out.close(); (1) generates an IOException (2) generates an ArrayIndexOutOfBoundsException
The try Block Enclose the code that might throw an exception within a try block try { code } catch and finally blocks... code contains one or more legal lines of code that could throw an exception
The try Block public void writelist() { PrintWriter out = null; try { System.out.println("Entered try statement"); out = new PrintWriter(new FileWriter("OutFile.txt")); for (int i = 0; i < SIZE; i++) out.println("value at: " + i + " = " + list.get(i)); catch and finally statements...
The catch Blocks Associate exception handlers with a try block by providing one or more catch blocks directly after the try block No code can be between the end of the try block and the beginning of the first catch block try { } catch (ExceptionType name) { } catch (ExceptionType name) { }
The catch Blocks try { } catch (FileNotFoundException e) { System.err.println("FileNotFoundExcepti on: " + e.getmessage()); throw new SampleException(e); catch (IOException e) { System.err.println("Caught IOException: " + e.getmessage());
The finally Block Always executes when the try block exits Used to put cleanup code Exp: 1) The new FileWriter statement fails and throws an IOException. 2) The list.get(i) statement fails and throws an ArrayIndexOutOfBoundsException. 3) Everything succeeds and the try block exits normally.
The finally Block finally { if (out!= null) { System.out.println("Closing PrintWriter"); out.close(); else { System.out.println("PrintWriter not open");
The finally Block try { out.close(); //Don't do this; it duplicates code. catch (FileNotFoundException e) { System.err.println("Caught: FileNotFoundException: " + e.getmessage()); throw new RuntimeException(e); catch (IOException e) { out.close(); //Don't do this; it duplicates code. System.err.println("Caught IOException: " + e.getmessage());
The finally Block Important: The finally block is a key tool for preventing resource leaks. When closing a file or otherwise recovering resources, place the code in a finally block to insure that resource is always recovered.
Specifying the Exceptions Thrown by a Method Sometimes, it's appropriate for code to catch exceptions that can occur within it. In other cases, it's better to let a method further up the call stack handle the exception. public void writelist() throws IOException, ArrayIndexOutOfBoundsException { } public void writelist() throws IOException{ }
How to Throw Exceptions Who can throw an exception? your code code from a package written by someone else such as the packages that come with the Java platform the Java runtime environment Always thrown with the throw statement
How to Throw Exceptions The Java platform provides numerous exception classes All the classes are descendants of the Throwable class throw somethrowableobject;
The throw Statement Requires a single argument: a throwable object instances of any subclass of the Throwable class public Object pop() { Object obj; if (size == 0) throw new EmptyStackException(); obj = objectat(size - 1); setobjectat(size - 1, null); size--; return obj; }
Throwable Class and Its Subclasses
Error and exception classes An Error: a dynamic linking failure or other hard failure in the Java virtual machine occurs simple programs typically do not catch or throw Errors An Exception: indicates that a problem occurred, but it is not a serious system problem most programs throw and catch objects that derive from the Exception class
Runtime Exceptions indicate incorrect use of an API NullPointerException which occurs when a method tries to access a member of an object through a null reference
Creating Exception Classes When to create an exception class? you need an exception type that isn't represented by those in the Java platform it helps users if they could differentiate your exceptions from the predefined ones the code throws more than one related exception
Creating Exception Classes A linked list class objectat(int n) throws an exception if n<0 or n> the number of objects currently in the list. firstobject() throws an exception if the list is empty. indexof(object o) throws an exception if the object passed into the method is not in the list.
Creating Exception Classes One possible class hierarchy for the exceptions thrown by the linked list
Unchecked Exceptions If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception.
Advantage 1: Separating Error-Handling Code from "Regular" Code readfile { open the file; determine its size; allocate that much memory; read the file into memory; close the file;
Advantage 1: Separating Error- Handling Code from "Regular" Code What happens if the file can't be opened? What happens if the length of the file can't be determined? What happens if enough memory can't be allocated? What happens if the read fails? What happens if the file can't be closed?
Advantage 1: Separating Error-Handling Code from "Regular" Code errorcodetype readfile { initialize errorcode = 0; open the file; if (thefileisopen) { determine the length of the file; if (gotthefilelength) { allocate that much memory; if (gotenoughmemory) { read the file into memory; if (readfailed) errorcode = -1; } else errorcode = -2;} else errorcode = -3; } close the file; if (thefiledidntclose && errorcode == 0) { errorcode = -4; } else { errorcode = errorcode and -4; } } else { errorcode = -5; } return errorcode; }
Advantage 1: Separating Error-Handling Code from "Regular" Code readfile { try { open the file; determine its size; allocate that much memory; read the file into memory; close the file; } catch (fileopenfailed) { dosomething; } catch (sizedeterminationfailed) { dosomething; } catch (memoryallocationfailed) { dosomething; } catch (readfailed) { dosomething; } catch (fileclosefailed) { dosomething; }
Advantage 2: Propagating Errors Up the Call Stack method1 { call method2; } method2 { call method3; } method3 { call readfile; }
Advantage 2: Propagating Errors Up the Call Stack method1 { errorcodetype error; error = call method2 if (error) doerrorprocessing; else proceed;} errorcodetype method2 { errorcodetype error; error = call method3; if (error) return error; else proceed;} errorcodetype method3 { errorcodetype error; error = call readfile; if (error) return error; else proceed; }
Advantage 2: Propagating Errors Up the Call Stack method1 { try { call method2; catch (exception e) { doerrorprocessing; method2 throws exception { call method3; method3 throws exception { call readfile;
Advantage 3: Grouping and Differentiating Error Types java.io > IOException descendant FileNotFoundException catch (IOException e) {... or catch (FileNotFoundException e) {... or catch (Exception e) { //A (too) general exception handler...
Problem Read data from the file Input.txt. The file should contain integer numbers, one per row. If the read value is an integer number, place it into the file Output.txt, otherwise generate an exception. The exception s handler should read a number from the keyboard and put it into the Output.txt file.
Solution public class MyException extends Exception{ private String s; private int row; public MyException(int r, String line){ s=line; row=r; } public String tostring(){ return String.format("Exception in line %d to the String %s", row, s);}
Solution import java.io.*; public class Client{ public static void main(string []arg){ BufferedReader in=null, ink=null; PrintStream out=null; String line; int row=1;
Solution try{ in = new BufferedReader(new InputStreamReader( new FileInputStream("Input.txt"))); ink = new BufferedReader(new InputStreamReader( System.in)); out = new PrintStream(new FileOutputStream("Output.txt")); //Read procedure catch(ioexception e) { System.out.println(e);}
Solution //Read procedure line=in.readline(); while(line!=null){ try{ for(int i=0;i<line.length();i++) if(!character.isdigit(line.charat(i))) throw new MyException(row, line); out.println(line); line=in.readline(); row++;} catch(myexception e){ System.out.println(e); System.out.println("Read a number from the keyboard"); line=ink.readline(); out.println(line);}}
Solution try{ //Previously presented } finally { try{ if(in!=null) in.close(); if(ink!=null) ink.close(); if(out!=null) out.close();} catch(ioexception e){ System.out.println(e);}
References The Java Tutorials. Exceptions. http://java.sun.com/docs/books/tuto rial/essential/exceptions/index.html