1 / 30

Exception

Exception. Exceptions Handling. Exceptions are error conditions from which a program can recover from Examples of exception include Using an Array index greater than the array size Trying to use an object reference that refers nowhere Trying to open a file that does not exist

nolasco
Download Presentation

Exception

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Exception For use of Cleveland State's IST410 Students only

  2. Exceptions Handling • Exceptions are error conditions from which a program can recover from • Examples of exception include • Using an Array index greater than the array size • Trying to use an object reference that refers nowhere • Trying to open a file that does not exist • Decisions to be made in a program include • Should the error condition be trapped • Recovery action to be taken in case of error • Untrapped error conditions leads to program failure 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 } For use of Cleveland State's IST410 Students only

  4. Partial Exception Hierarchy Throwable Error Exception VirtualMachineError AWTError RuntimeException IOException NullPointerException ArithmeticException EOFException For use of Cleveland State's IST410 Students only

  5. Exception Hierarchy • All exceptions are derived from Throwable • Only objects that are instances of Throwable are thrown by JVM, or can be thrown by throw statement • Throwable has 2 known subclasses: Error, Exception • Error indicates serious problems that an application normally does not try to recover from • Direct Subclasses of Error: • AWTError, LinkageError, ThreadDeath, VirtualMachineError • Exception indicates problems that an application might catch For use of Cleveland State's IST410 Students only

  6. RuntimExceptions class • Some of the direct subclasses of Exception are: RuntimeException, and IOException (and others) • RuntimeException happens mostly due to programming error • Examples • ArithmeticException - ex. wrong arithmetic expression • IndexOutOfBoundsException - exceed the array boundaries • NumberFormatException - bad convert from String to number • Should a program try to recover from these errors? For use of Cleveland State's IST410 Students only

  7. Other Exceptions • Exceptions that do not fall into RuntimeException category indicate error conditions that are not necessarily due to coding errors • These exceptions are also known as checked exception • Compiler enforces declaration of checked exception • Examples • FileNotFoundException - file not found • ObjectStreamException - Error in Object Streams • A program may attempt to deal with such exceptions For use of Cleveland State's IST410 Students only

  8. Code that may cause Exceptions try { // code or Methods that may cause exception } • Code that may cause exception(s) are put in a try block • 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 } For use of Cleveland State's IST410 Students only

  9. throws • A method may ‘throws’ more than one exception public int getNumber(String s) throws NullPointerException, NumberTooBigException { // method code goes here } • Unchecked exceptions may also be thrown by a method For use of Cleveland State's IST410 Students only

  10. Throwing an Exception • 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; } • When an exception is thrown in a method, it is an implicit return unless the there is a local catch or finally block For use of Cleveland State's IST410 Students only

  11. Throwing an Exception • 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 } For use of Cleveland State's IST410 Students only

  12. Catching an Exception • As you can see, exception is a type of object • 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”); } • A method may catch its own exception or throw the exception to its caller For use of Cleveland State's IST410 Students only

  13. Catching an Exception • 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”); } • Multiple catches are ordered so that exception types are listed from the lowest to the highest level in the exception hierarchy For use of Cleveland State's IST410 Students only

  14. Catching an Exception • A catch clause normally provides error handling mechanism • Sometimes we may just dump the exception stack try { int i = getNumber(“234”) } catch (NullPointerException np) { np.printStackTrace(); } .... For use of Cleveland State's IST410 Students only

  15. Catching an Exception • 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) { } } .... For use of Cleveland State's IST410 Students only

  16. Rethrowing an Exception • 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; } .... • Of course, the method then must have a throws clause For use of Cleveland State's IST410 Students only

  17. Orderly Exit from Exception • Sometimes we may want to ensure a trailing action, exception or no exception • 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 } 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); } } For use of Cleveland State's IST410 Students only

  19. Exception from Constructor • 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; } ..... For use of Cleveland State's IST410 Students only

  20. Defining one’s own Exception Class • A program can use Exceptions defined in Java Language • A program can define its own exception class • A program defined exception is created by extending an Exception class • For example public class NegativeNumberException extends Exception { // implementation of the class } • You may recall that Exception is a subclass of Throwable • User defined exceptions are always checked exception type For use of Cleveland State's IST410 Students only

  21. Throwable • Throwable is the super class of exception/error conditions • It has 2 constructors • Throwable() • Throwable(String msg) • msg defines the error message with which the error object can be initialized with • The error message can be printed with • getMessage() • getMessage() returns the msg string with which the throwable object was constructed For use of Cleveland State's IST410 Students only

  22. Throwable • 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 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(); } } For use of Cleveland State's IST410 Students only

  24. Extending user-defined Exception class • 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(); } } For use of Cleveland State's IST410 Students only

  25. Comprehensive examples • TestNumberException.java • notice the source file format • Example from Java in a Nutshell • throwtest.java • MyException.java • MyOtherException.java • MySubException.java For use of Cleveland State's IST410 Students only

  26. Exception and overriding • A method that overrides another method from a superclass must throw • Exactly same exception types as the overriden method; or • Subclasses of exception types thrown by the overriden method; or • A subset of exceptions thrown by the superclass method • Implications • No new Exception can be thrown by the subclass method unless it satisfies at least one of the above conditions • Notice the number of exceptions thrown by the subclass method is not a factor if the conditions above are met For use of Cleveland State's IST410 Students only

  27. Exception and overriding: Examples • Superclass method public void methodOne() throws IndexOutOfBoundsException { ... } • Subclass method public void methodOne() throws ArrayIndexOutOfBoundsException { .. } • The overriding method is legal since ArrayIndexOutOfBoundsException is a subclass of IndexOutOfBoundsException For use of Cleveland State's IST410 Students only

  28. Exception and overriding: Examples • Superclass method public void methodOne() throws IndexOutOfBoundsException { ... } • Subclass method public void methodOne() throws RuntimeException { .. } • The overriding method is NOT legal since RuntimeException is NOT a subclass of IndexOutOfBoundsException For use of Cleveland State's IST410 Students only

  29. Exception and overriding: Examples • Superclass method public void methodOne() throws Exception { ... } • Subclass method public void methodOne() throws ArithmeticException, NullPointerException { .. } • The overriding method is legal since both ArithmeticException and NullPointerException are subclasses Exception For use of Cleveland State's IST410 Students only

  30. Exception and overriding: Examples • Superclass method public void methodOne() throws ArithmeticException, NullPointerException { ... } • Subclass method public void methodOne() throws ArithmeticException { .. } • The overriding method is legal since the exception thrown by the subclass method is a proper subset of exceptions thrown by the superclass method For use of Cleveland State's IST410 Students only

More Related