1 / 30

Exceptions

Exceptions. Exceptions. Many problems in code are handled when the code is compiled, but not all Some are impossible to catch before the program is run Must run the program to actually determine the values of variables, get user input, etc.

eric-perry
Télécharger la présentation

Exceptions

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

  2. Exceptions • Many problems in code are handled when the code is compiled, but not all • Some are impossible to catch before the program is run • Must run the program to actually determine the values of variables, get user input, etc. • These errors that occur when the program is running are “exceptions”

  3. Exceptions • An exception is an object that describes an unusual or erroneous situation • Exceptions are generated by part of a program, and may be handled by another part of the program • A program can be separated into a normal execution flow and an exception execution flow • An error is also represented as an object in Java, but usually represents a unrecoverable situation and should not be caught

  4. Exception Handling • Java has a predefined set of exceptions and errors that can occur during execution • A program can deal with an exception in one of three ways: • ignore it • handle it where it occurs • handle it an another place in the program • The manner in which an exception is processed is an important design consideration

  5. Exception Handling • If an exception isn’t handled by the program, it halts and prints an error: Exception in thread “main” java.lang.NullPointerException at SomeClass.method(SomeClass.java:54) at Except.e2(Except.java:12) at Except.main(Except.java:22) • The error message gives the type of exception that was thrown (NullPointerException) • and the “stack trace”…

  6. The Call Stack Trace • Indicates the line on which the exception occurred • (SomeClass.java:54) • Shows the method call trail that lead to the attempted execution of the offending line • main→ e2 → method

  7. Tracing Problems • The call stack can be very long, and call methods in many libraries Exception in thread “main” java.util.UnknownFormatConversionException: Conversion = ‘i’ at java.util.Formatter$FormatSpecifier.conversion(Formatter.java:2603) at java.util.Formatter$FormatSpecifier.<init>(Formatter.java:2631) at java.util.Formatter.parse(Formatter.java:2477) at java.util.Formatter.format(Formatter.java:2411) at java.io.PrintStream.format(PrintStream.java:899) at java.io.PrintStream.printf(PrintStream.java:800) at Except.e3(Except.java:17) at Except.main(Except.java:22) • It can be tricky to find the “real” cause • should be the innermost code that isn’t fully tested

  8. The Exception Class • In Java, exceptions are objects • There is a hierarchy of exception types, with Exception at the top • you don’t generally instantiate Exception; one is automatically created when there is an error • There are many subclasses of Exception that are used for particular types of errors

  9. Exception Subclasses • The subclasses of Exception are types that more specifically identify the problem, e.g.: • ArithmeticException • most often caused by a divide-by-zero • IndexOutOfBoundsException • array/List/String index doesn’t exist • NoClassDefFoundError • .class file was there when compiling, but not there now • Tend to have informative names: useful errors

  10. The Exception Class Hierarchy • All error and exception classes are descendents of the Throwable class • A programmer can define an exception by extending the Exception class or one of its descendants • The parent class used depends on how the new exception will be used

  11. Catching Exceptions • We say that a certain block of code “throws” an exception • think: when the exception occurs, an exception object is generated and tossed at the interpreter • How do you handle something that is thrown at the interpreter? • you “catch” it • Uncaught exceptions stop the program… caught exceptions do not

  12. The try Statement • To handle an exception in a program, the line that throws the exception is executed within a try block • A try block is followed by one or more catch clauses • Each catch clause has an associated exception type and is called an exception handler • When an exception occurs, processing continues at the first catch clause that matches the exception type

  13. A try/catch sequence try { \\ execute the code that you find here } catch(Exception e) { \\ if the there is an exception \\ then you do the stuff in this part }

  14. An Example try { int x; x = 10/0; } catch(Exception e) { System.out.println(“error occurred”); }

  15. The Exception Parameter • The catch is a little like an else, and a little like a function definition • try {…} catch(Exception e) {…} • The argument (“exception parameter”) is assigned to an appropriate Exception object • In the divide-by-zero example, e will be an instance of ArithmeticException • The exception parameter’s value can be ignored if you don’t need to use it

  16. Another Example try { int x; x = 10/0; } catch(ArithmeticException e) { System.out.println(“divided by 0”); }

  17. Being Specific • Can have multiple catch blocks • The exception parameter type allows different types of exceptions to be handled differently

  18. Being Specific try { int x = userin.nextInt(); System.out.println(10/x); } catch(ArithmeticException e) { System.out.println(“no zeroes”); } catch(InputMismatchException e) { System.out.println(“enter a number”); } Most likely causes

  19. Being Specific • The exception parameter is matched like arguments in an overloaded function • The type of exception thrown is matched against the exception parameters • That class… or any subclass… will match • Examples: • Exception matches all exceptions • IndexOutOfBounds matches both array and string exceptions

  20. The Catch All try { … a bunch of code, involving an integer x… System.out.println(10/x); } catch(ArithmeticException e) { System.out.println(“no zeroes”); } catch(Exception e) { System.out.println(“some other problem”); }

  21. However… • In general, use a type as specific as possible • only catch the exceptions you want to catch and handle properly • Don’t incorrectly handle other problems • the catch-all hides problems you might want to know about • Other exceptions are propogated • they can be caught farther up the call stack

  22. Exception Propagation • An exception can be handled at a higher level if it is not appropriate to handle it where it occurs • Exceptions propagate up through the method calling hierarchy until they are caught and handled or until they reach the level of the main method • A try block that contains a call to a method in which an exception is thrown can be used to catch that exception

  23. Checked versus Unchecked • An exception is either checked or unchecked • An unchecked exception does not require explicit handling, though it could be processed that way • The only unchecked exceptions in Java are objects of type RuntimeException or any of its descendants • Errors are similar to RuntimeException and its descendants in that: • Errors should not be caught • Errors do not require a throws clause

  24. Checked Exceptions • Checked exceptions (other subclasses of Exception) must be handled explicitly • must be caught by a method in a catch block • must be listed in the throws clause of any method that might throw it • The compiler will issue an error if a checked exception is not caught or asserted in a throws clause

  25. The throws Clause • Used to indicate that the method will “handle” the checked exception by passing it off to the calling code • Similarly, the calling code must either catch it or be declared indicating that it throws the exception public int myMethod() throws Exception1, Exception2 • Any uncaught checked exceptions must be listed in the throws clause

  26. The throw Statement • When your code gets to a situation it can’t handle, it can throw an exception • e.g. constructor/setter given an illegal value • Create an instance of the appropriate exception class • new SomeException(“Error message”); • Throw the exception with a throw statement • throw new SomeException(“message”);

  27. The throw Statement • The throw statement appears in the body of a method, with an appropriate throws clause • Usually a throw statement is executed inside an if statement that evaluates a condition to see if the exception should be thrown if(x<0) throw new NegativeInputException;

  28. Example • From the Student class: public void setFirstName(String name) { if(name.length()>0) firstName = name; else throw new IllegalArgumentException (“Name must have length >0”); }

  29. The finally Clause • A try statement can have an optional clause following the catch clauses, designated by the reserved word finally • The statements in the finally clause always are executed • If no exception is generated, the statements in the finally clause are executed after the statements in the try block complete • If an exception is generated, the statements in the finally clause are executed after the statements in the appropriate catch clause complete

  30. Why use finally ? • To make sure that a certain part of an algorithm are executed • To leave objects in a stable state • e.g. An object representing a database connection might be disconnected when an error occurs • … there are good security reasons for doing this

More Related