Presentation is loading. Please wait.

Presentation is loading. Please wait.

Java Exceptions. Exceptions Often in computing, operations cannot properly execute because some sort of error has occurred. Some examples: Often in computing,

Similar presentations


Presentation on theme: "Java Exceptions. Exceptions Often in computing, operations cannot properly execute because some sort of error has occurred. Some examples: Often in computing,"— Presentation transcript:

1 Java Exceptions

2 Exceptions Often in computing, operations cannot properly execute because some sort of error has occurred. Some examples: 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.

3 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. 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; result = 100/num;}else{ //print error //print error //get new value //get new value //do more stuff //do more stuff}……

4 Java Exceptions The error checking and recovery breaks up the flow of normal processing. 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: 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. Exception handling allows programmers to handle exceptional cases outside the normal flow of control.

5 Addition Example We saw earlier that our Addition class did not catch possible exceptions. 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.

6 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...

7 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; } …

8 Exception Hierarchy

9 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

10 Java Exceptions In Java the Exception class defines mild error conditions that your programs might encounter. 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. Rather than blindly terminating the program, you can write code to handle your exceptions and continue executing the program. RunTimeException RunTimeException Other type of Exceptions (We call them Non RunTimeException) Other type of Exceptions (We call them Non RunTimeException)

11 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

12 try/catch try/catch blocks are used to catch and handle exceptions try{ … //normal flow of program } catch(Exceptiontype reference) { … //exception handler code }

13 try/catch If an exception occurs within a try block, all catch blocks will be searched for a matching exception type. 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 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. The exception can be thrown from within a method and be handled by the caller.

14 try/catch Catch blocks specify different types (All derived from ‘Throwable’) of exceptions. 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. 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 Once the block is done executing, flow of control will pick up after the last catch block

15 try/catch If an exception is not caught locally, the next enclosing try/catch block will be tested. 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. The order of enclosing try/catch blocks will follow the call stack.

16 finally The finally statement defines a block of code that always executes regardless of whether an exception was caught. try {//protected code startFaucet(); startFaucet(); waterLawn(); waterLawn();} catch(Exception e) { //handle exception //handle exception}finally{ stopFaucet(); stopFaucet();}

17 What need to be done for the three types of exceptions There are two types of exceptions in Java: 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

18 Common Exceptions –ArithmeticException –NullPointerException –NegativeArraySizeException –ArrayIndexOutOfBoundsException –SecurityException –IOException

19 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. 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 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

20 Handle or Declare Rule To indicate that the calling method will not handle the exception use the keyword throws in the method definition. 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 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 This rule only applies for exceptions derived from Exception but not derived from RuntimeException

21 Try, Catch, Finally try tryblock tryblock catch (exception_type identifier) catchblock catchblock catch (exception_type identifier) catchblock catchblock // 0 or more of these finally // 0 or 1 of these finallyblock finallyblock

22 Try, Catch and Finally Execute tryblock of statements until either an exception is thrown or the block finishes successfully. 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 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. 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. The finally block is always executed, even if no exceptions are thrown.

23 Another try/catch example public static String readString() { int ch; String r = ""; boolean done = false; while (!done) { try { ch = System.in.read(); /* try block */ if (ch < 0 || (char)ch == `\n’) done = true; else r = r + (char) ch; } catch(IOException e) /* catch clause */ { done = true; /* } handler code */ }; return r; }

24 Propagating an Exception if you call a method that throws a checked exception, you must either handle it or propagate it. 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 propagate an Exception by adding a throw clause in the method header

25 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; }

26 Finally Example public boolean searchFor(String file, String word) throws StreamException { throws StreamException { try { try { input = new Stream(file); input = new Stream(file); while (!input.eof()) while (!input.eof()) if ((input.next()).equals(word)) if ((input.next()).equals(word)) return true; //word found return true; //word found return false; //word not found return false; //word not found } finally { // finally block is executed whether or not try throws an exception. // finally block is executed whether or not try throws an exception. if (input != null) if (input != null) input.close(); }} input.close(); }}

27 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. 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() printStackTrace() getMessage() getMessage()

28 main() { fie(); fie();} fie() { foo(); foo();} foo() { int i=1; int i=1; int j=0; int j=0; i = i/j; 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.

29 Throwing Exception Exceptions are thrown (signaled) when 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)

30 Example 1 class ImplicitThrow { public static main(String[ ] args) { int i = 1, j=0, k; int i = 1, j=0, k; k= i/j; k= i/j; System.out.println("k is " + k); System.out.println("k is " + k);}} Throws an ArithmeticException Unchecked exceptions need not be declared

31 Example 2 class MethodThrows { public Image loadImage(String source) public Image loadImage(String source) throws MalformedURLException, IOException { throws MalformedURLException, IOException { URL url = new URL(source); URL url = new URL(source); InputStream in = url.openStream() InputStream in = url.openStream() }} Throws MalformedURLException, IOException Throws MalformedURLException, IOException Method Must declare checked exceptions Method Must declare checked exceptions

32 Explicitly Throw an Exception Find an appropriate exception class from the API (or define your own by subclassing Exception ) Find an appropriate exception class from the API (or define your own by subclassing Exception ) create an object of that class create an object of that class throw it throw it Thrown exceptions dealt with by calling method. This declaration forces calling method to catch exception or propagate it. Thrown exceptions dealt with by calling method. This declaration forces calling method to catch exception or propagate it. Rethrow? Rethrow?

33 Example 3 String readInput (BufferedReader in) throws EOFException /* throw clause */ {... while (...) { if (ch == -1) /* EOF encountered */ { if (n < len) throw new EOFException(); }... } return s; }

34 Another Explicit throw class MyExceptionThrow { public String readLines(DataInputStream in) public String readLines(DataInputStream in) throws FewLinesException, IOException { throws FewLinesException, IOException { int length = 1024, n = 0; int length = 1024, n = 0; String line; String line; line=in.readline(); line=in.readline(); while (line!= null) { while (line!= null) { n++; line = in.readLine(); n++; line = in.readLine(); } if (n < length) throw new FewLinesException(); if (n < length) throw new FewLinesException(); // Throw user defined exception // Throw user defined exception else return "Enough lines read in!"; else return "Enough lines read in!"; } } } }

35 Define your own Exception types Exception classes can have constructors, methods, polymorphic methods, etc… Exception classes can have constructors, methods, polymorphic methods, etc… class FewLinesException extends IOException { public FewLinesException() { } public FewLinesException() { } public FewLinesException(String msg) { public FewLinesException(String msg) { super(msg); super(msg); }}

36 Handling Checked Exceptions If you invoke a method that lists a checked exception in its throws clause, you must either: 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

37 Must deal with thrown exceptions import java.net.*; class Except1 { static URL imageURL; static URL imageURL; public static URL getURL(String urlstr) { public static URL getURL(String urlstr) { return new URL(urlstr); return new URL(urlstr); } public static void main(String[] args) { public static void main(String[] args) { imageURL = getURL("haha"); 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 method

38 RuntimeException and Non- RuntimeException Non-RuntimeException Non-RuntimeException –must be caught –or declared in the throws clause of any method that can throw them. Subclasses of RuntimeExceptio n, Error Subclasses of RuntimeExceptio n, Error –unchecked exceptions (not required to explicitly catch)

39 Still Complain import java.net.*; class Except1 { static URL imageURL; static URL imageURL; public static URL getURL(String urlstr) public static URL getURL(String urlstr) throws MalformedURLException{ throws MalformedURLException{ return new URL(urlstr); return new URL(urlstr); } public static void main(String[] args) { public static void main(String[] args) { imageURL = getURL("haha"); imageURL = getURL("haha"); }}

40 No compile complain import java.net.*; class Except1 { static URL imageURL; static URL imageURL; public static URL getURL(String urlstr) public static URL getURL(String urlstr) throws MalformedURLException{ throws MalformedURLException{ return new URL(urlstr); return new URL(urlstr); } public static void main(String[] args) public static void main(String[] args) throws MalformedURLException{ throws MalformedURLException{ imageURL = getURL("haha"); imageURL = getURL("haha");}} Run-time complain

41 Inheritance and Exception Handling It is good practice to define your own exception types. It is good practice to define your own exception types. Inheritance can be used. Inheritance can be used. It is good practice to define your own exception types. It is good practice to define your own exception types. Catch exception object of superclass type allows for polymorphic processing of related errors Catch exception object of superclass type allows for polymorphic processing of related errors

42 Java Exceptions and Inheritance

43


Download ppt "Java Exceptions. Exceptions Often in computing, operations cannot properly execute because some sort of error has occurred. Some examples: Often in computing,"

Similar presentations


Ads by Google