Download presentation
Presentation is loading. Please wait.
Published byJamal Biscoe Modified over 9 years ago
1
For use of Cleveland State's IST410 Students only 1 Exception
2
For use of Cleveland State's IST410 Students only 2 Exceptions Handling l Exceptions are error conditions from which a program can recover from l Examples of exception include m Using an Array index greater than the array size m Trying to use an object reference that refers nowhere m Trying to open a file that does not exist l Decisions to be made in a program include m Should the error condition be trapped m Recovery action to be taken in case of error l Untrapped error conditions leads to program failure
3
For use of Cleveland State's IST410 Students only 3 Exception handling construct try { // code that may cause exception } catch (ExceptionType1 et1) { // code to handle ExceptionType1 } catch (ExceptionType2 et2) { // code to handle ExceptionType2 } finally { // code }
4
For use of Cleveland State's IST410 Students only 4 Partial Exception Hierarchy Throwable ErrorException AWTError VirtualMachineError RuntimeException IOException NullPointerExceptionArithmeticException EOFException
5
For use of Cleveland State's IST410 Students only 5 Exception Hierarchy l All exceptions are derived from Throwable l Only objects that are instances of Throwable are thrown by JVM, or can be thrown by throw statement l Throwable has 2 known subclasses: Error, Exception l Error indicates serious problems that an application normally does not try to recover from l Direct Subclasses of Error: m AWTError, LinkageError, ThreadDeath, VirtualMachineError l Exception indicates problems that an application might catch
6
For use of Cleveland State's IST410 Students only 6 RuntimExceptions class l Some of the direct subclasses of Exception are: RuntimeException, and IOException (and others) l RuntimeException happens mostly due to programming error l Examples m ArithmeticException - ex. wrong arithmetic expression m IndexOutOfBoundsException - exceed the array boundaries m NumberFormatException - bad convert from String to number l Should a program try to recover from these errors?
7
For use of Cleveland State's IST410 Students only 7 Other Exceptions l Exceptions that do not fall into RuntimeException category indicate error conditions that are not necessarily due to coding errors l These exceptions are also known as checked exception l Compiler enforces declaration of checked exception l Examples m FileNotFoundException - file not found m ObjectStreamException - Error in Object Streams l A program may attempt to deal with such exceptions
8
For use of Cleveland State's IST410 Students only 8 Code that may cause Exceptions try { // code or Methods that may cause exception } l Code that may cause exception(s) are put in a try block l Checked exceptions that are not handled in a method, but thrown, must be declared using a throws clause public int getNumber(String s) throws NullPointerException { // method code goes here }
9
For use of Cleveland State's IST410 Students only 9 throws l A method may ‘throws’ more than one exception public int getNumber(String s) throws NullPointerException, NumberTooBigException { // method code goes here } l Unchecked exceptions may also be thrown by a method
10
For use of Cleveland State's IST410 Students only 10 Throwing an Exception l Example of throws usage public int getNumber(String s) throws NullPointerException, NumberTooBigException { if (s == null) throw new NullPointerException(); int i = Integer.parseInt(s); if ( i > 200) throw new NumberTooBigException(); return i; } l When an exception is thrown in a method, it is an implicit return unless the there is a local catch or finally block
11
For use of Cleveland State's IST410 Students only 11 Throwing an Exception l We can create exception objects and throw them public int getNumber(String s) throws NullPointerException, NumberTooBigException { if (s == null) { NullPointerException np = new NullPointerException(); throw np; } // rest of the method code }
12
For use of Cleveland State's IST410 Students only 12 Catching an Exception l As you can see, exception is a type of object l A method creates an exception object that someone must catch try { int i = getNumber(“234”) } catch (NullPointerException np) { System.out.println(“The String is empty”); } l A method may catch its own exception or throw the exception to its caller
13
For use of Cleveland State's IST410 Students only 13 Catching an Exception l A method may catch more than one exception types try { int i = getNumber(“234”) } catch (NullPointerException np) { System.out.println(“The String is empty”); } catch (NumberTooBigException ntb) { System.out.println(“Number greater than 200”); } catch (Exception e) { System.out.println(“Unforeseen Error”); } l Multiple catches are ordered so that exception types are listed from the lowest to the highest level in the exception hierarchy
14
For use of Cleveland State's IST410 Students only 14 Catching an Exception l A catch clause normally provides error handling mechanism l Sometimes we may just dump the exception stack try { int i = getNumber(“234”) } catch (NullPointerException np) { np.printStackTrace(); }....
15
For use of Cleveland State's IST410 Students only 15 Catching an Exception l Sometimes we may retry the code, note nesting try { int i = getNumber(“234”) } catch (NullPointerException np) { System.out.println(“Number was too big, retry”); try { int j = getNumber(“103”); } catch (NullPointerException np1) { } }....
16
For use of Cleveland State's IST410 Students only 16 Rethrowing an Exception l Sometimes we may partially handle the exception and then rethrow for some other method to complete handling try { int i = getNumber(“234”) } catch (NullPointerException np) { System.out.println(“Number was too big, retry”); throw np; }.... l Of course, the method then must have a throws clause
17
For use of Cleveland State's IST410 Students only 17 Orderly Exit from Exception l Sometimes we may want to ensure a trailing action, exception or no exception l finally clause enables us to do just that try { int i = getNumber(“234”) } catch (NullPointerException np) { System.out.println(“Number was too big, retry”); } finally { // exit code }
18
For use of Cleveland State's IST410 Students only 18 Simple Example public class SimpleException { public static void main(String [] args) { int anIntegerNumber; try { anIntegerNumber = Integer.parseInt(args[0]); } catch (ArrayIndexOutOfBoundsException e) { // args is empty System.out.println("Must specify an argument"); return; } catch (NumberFormatException e) { // args[0] is not an integer System.out.println("Must specify an integer"); return; } finally { System.out.println("This line is printed, error or no error"); } System.out.println("Command line value is "+anIntegerNumber); }
19
For use of Cleveland State's IST410 Students only 19 Exception from Constructor l Constructor is a method and can throw an exception public class Point { private int x, y; public Point(int x, int y) throws NegativeNumberException { if (x < 0 || y < 0) throw new NegativeNumberException(); this.x = x; this.y = y; }.....
20
For use of Cleveland State's IST410 Students only 20 Defining one’s own Exception Class l A program can use Exceptions defined in Java Language l A program can define its own exception class l A program defined exception is created by extending an Exception class l For example public class NegativeNumberException extends Exception { // implementation of the class } l You may recall that Exception is a subclass of Throwable l User defined exceptions are always checked exception type
21
For use of Cleveland State's IST410 Students only 21 Throwable l Throwable is the super class of exception/error conditions l It has 2 constructors m Throwable() m Throwable(String msg) l msg defines the error message with which the error object can be initialized with l The error message can be printed with m getMessage() l getMessage() returns the msg string with which the throwable object was constructed
22
For use of Cleveland State's IST410 Students only 22 Throwable l It is possible to find out the name of the error object itself using np.getClass().getName() where np Appropriate error object getClass()Returns the class object associated with np getName()Returns the name of the class
23
For use of Cleveland State's IST410 Students only 23 Sample user-defined Exception class public class NegativeNumberException extends Exception { public NegativeNumberException(String msg) { super(msg); } public NegativeNumberException() { super(); }
24
For use of Cleveland State's IST410 Students only 24 Extending user-defined Exception class l An use-defined exception class can also extend another user-defined exception class class NegativeIntegerException extends NegativeNumberException { public NegativeIntegerException(String msg) { super(msg); } public NegativeIntegerException() { super(); }
25
For use of Cleveland State's IST410 Students only 25 Comprehensive examples l TestNumberException.java m notice the source file format l Example from Java in a Nutshell m throwtest.java m MyException.java m MyOtherException.java m MySubException.java
26
For use of Cleveland State's IST410 Students only 26 Exception and overriding l A method that overrides another method from a superclass must throw m Exactly same exception types as the overriden method; or m Subclasses of exception types thrown by the overriden method; or m A subset of exceptions thrown by the superclass method l Implications m No new Exception can be thrown by the subclass method unless it satisfies at least one of the above conditions l Notice the number of exceptions thrown by the subclass method is not a factor if the conditions above are met
27
For use of Cleveland State's IST410 Students only 27 Exception and overriding: Examples l Superclass method public void methodOne() throws IndexOutOfBoundsException {... } l Subclass method public void methodOne() throws ArrayIndexOutOfBoundsException {.. } l The overriding method is legal since ArrayIndexOutOfBoundsException is a subclass of IndexOutOfBoundsException
28
For use of Cleveland State's IST410 Students only 28 Exception and overriding: Examples l Superclass method public void methodOne() throws IndexOutOfBoundsException {... } l Subclass method public void methodOne() throws RuntimeException {.. } l The overriding method is NOT legal since RuntimeException is NOT a subclass of IndexOutOfBoundsException
29
For use of Cleveland State's IST410 Students only 29 Exception and overriding: Examples l Superclass method public void methodOne() throws Exception {... } l Subclass method public void methodOne() throws ArithmeticException, NullPointerException {.. } l The overriding method is legal since both ArithmeticException and NullPointerException are subclasses Exception
30
For use of Cleveland State's IST410 Students only 30 Exception and overriding: Examples l Superclass method public void methodOne() throws ArithmeticException, NullPointerException {... } l Subclass method public void methodOne() throws ArithmeticException {.. } l The overriding method is legal since the exception thrown by the subclass method is a proper subset of exceptions thrown by the superclass method
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.