1 / 18

Java Exceptions

Java Exceptions. Intro to Exceptions. What are exceptions? Events that occur during the execution of a program that interrupt the normal flow of control. One technique for handling Exceptions is to use return statements in method calls.

tanner
Télécharger la présentation

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

  2. Intro to Exceptions • What are exceptions? • Events that occur during the execution of a program that interrupt the normal flow of control. • One technique for handling Exceptions is to use return statements in method calls. • This is fine, but java provides a much more general and flexible formalism that forces programmers to consider exceptional cases.

  3. Exception Class hierarchy Object • must handle • may handle • too serious to catch Throwable Error Exception many RuntimeException IndexOutOfBounds NullPointerException

  4. Catch orSpecify requirement • Most Exceptions in Java are subject to the so-called “catch or specify” requirement. • That is, to call a method that is declared to throw an Exception, one must explicitly wrap the call in a try block: try{ File f = new File(“foo.txt”) Catch(FileNotFoundException fnfe){…} } … or one must specify the Exception in the method signature where the method call appears public void foo() throws FileNotFoundException

  5. Three kinds of Exceptions • I say most on previous slide because there are three different type of exeptions in Java and only one is subject to catch or specify: • Checked Exceptions: Must handle • Runtime Exceptions: May handle • Errors: May handle • Each of these types is represented by its own class in the Throwable hierarchy.

  6. Exception Handling Basics • Three parts to Exception handling 1. claiming exception 2. throwing exception 3. catching exception • A method has the option of throwing one or more exceptions when specified conditions occur. This exception must be claimed by the method. Another method calling this method must either catch or rethrow the exception. (unless it is a RuntimeException)

  7. Claiming Exceptions • Method declaration must specify every exception that the method potentially throws MethodDeclaration throws Exception1, Exception2, ..., ExceptionN • Exceptions themselves are concrete subclasses of Throwable and must be defined and locatable in regular way.

  8. Throwing Exception • To throw an Exception, use the throw keyword followed by an instance of the Exception class void foo() throws SomeException{ if (whatever) {...} else{ throw new SomeException(...)} • We’ll talk about passing data via the Exception constructor soon. • Note that if a method foo has a throw clause within it, that the Exception that is thrown (or one of its superclasses) must be claimed after the signature.

  9. Catching Exceptions • The third piece of the picture is catching exceptions. • This is what you will do with most commonly, since many of java’s library methods are defined to throw one or more runtime exception. • Catching exceptions: • When a method is called that throws and Exception e.g SomeException, it must be called in a try-catch block: try{ foo(); } catch(SomeException se){...}

  10. Catching Exceptions, cont. • Note that if a method throws an Exception that is NOT a RuntimeException, you must do one of two things: • try-catch it (often called handling it) • rethrow it • In the latter case, responsibility then moves up the calling chain to handle it, and so on all the way up to main.

  11. More on try-catch The general form of the try-catch structure is: try{ /* any number of lines of code that call any number of methods with any thrown Exceptions */ } catch(Exception1 e1){ /* do anything you want here e.g. change value and try again. print error and quit print stacktrace */ catch (Exception2 e2){ /* any number of exceptions can be handled ... */ }

  12. Example1 import java.io.*; public class Exception1{ public static void main(String[] args){ InputStream f; try{ f = new FileInputStream("foo.txt"); } catch(FileNotFoundException fnfe){ System.out.println(fnfe.getMessage()); } } }

  13. Example2 import java.io.*; public class Exception2{ public static void main(String[] args){ InputStream fin; try{ fin = new FileInputStream("foo.txt"); int input = fin.read(); } catch(FileNotFoundException fnfe){ System.out.println(fnfe.getMessage()); } catch(IOException ioe){ System.out.println(ioe.getMessage()); } }}

  14. import java.io.*; public class Exception2{ public static void main(String[] args){ InputStream fin; try{ fin = new FileInputStream("foo.txt"); int input = fin.read(); } catch(FileNotFoundException fnfe){ System.out.println(fnfe.getMessage()); } catch(IOException ioe){ System.out.println(ioe.getMessage()); } } }

  15. Recommendations • Do not use Exceptions to handle normal conditions in the program that can be checked with if statements. For example: • to find the end of an array • to check if an object is null • See other commented examples in course notes.

  16. finally clause • Java includes a third statement that often goes with try-catch blocks called finally • Code in a finally block is “guaranteed” to execute regardless of whether or not the catch block is executed. • Very common for closing open “resources” such as database connections, file handles, sockets, etc. that are not handled by the garbage collector. • finally makes code cleaner and less fragile but is not strictly necessary. Still, it is highly recommended.

  17. Example: closing PrintWriter private List<Integer> list; private static final int SIZE = 10; 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 . . .

  18. Creating your own Exceptions • You can follow this procedure exactly when creating your own Exception. • Create a class that subclasses Exception (or RuntimeException). • You may also add functionality so that a relevant message is stored when the error is thrown, and any other customized functionality you choose.

More Related