1 / 14

Java Exceptions

Java Exceptions. Dan Fleck CS211. What is an Exception . An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions. Intuition: It’s something you didn’t expect. What happens?.

sclaire
Download Presentation

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 Dan Fleck CS211

  2. What is an Exception • An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions. • Intuition: It’s something you didn’t expect

  3. What happens? • If an exception occurs an “Exception” object is created, and then passed up the call stack until someone handles it. main Exception Method 1: I’ll handle it Exception Method 2:I can’t Handle it Exception Catches I had a problem Forwards Call Stack Throws

  4. Catch or Specify • Code that can generate certain exceptions must either catch or specify it. • Catch: • try { … multiple statements …} catch (SpecificException specificExc) { … handle exception …} • Specify: • public void myMethod() throws SpecificException { … }

  5. Exception Types • Checked exceptions • Must satisfy the catch or specify requirement • Are subclasses of java.lang.Exception • Checked exceptions should be handled and recovered from • Examples: user types in a bad filename, etc…

  6. Exception Types (cont.) • Unchecked exceptions • Not subject to the catch or specify requirement • Errors - unforeseen error conditions due to external issues that an application probably cannot recover from. • Example: IOError when reading a file (due to bad sectors on the disk) • RuntimeExceptions - error conditions internal to the program that an application probably cannot recover from. • Generally these are programming errors or logic errors • Example: IllegalArgumentException - someone passed in an invalid argument to your program

  7. Why ever use checked? • You should almost always use checked exceptions. These exceptions allow a well-written program to catch and handle the condition. Only use unchecked when a reasonable program cannot deal with the problem.

  8. Catching exceptions • try { …. Code …} catch (Exception1 exc) { } catch (Exception2 exc) {} • Exceptions thrown in “code” are caught by the catch blocks. • Catch blocks catch exceptions in order, so put super-classes at the bottom (catch specific exceptions first) • Example:} catch (IOException ioe) { .. Do something specific to an IOException ..} catch (Exception e) { .. Catch all other general exceptions and do something for them}

  9. Finally -- the finally block • try { …. } catch (Exception e) { …. } finally { … Code …} • The finally block always executes when the try block completes. This is where you perform any cleanup needed after the try block completes successfully or throws an exception • Having a finally block is optional -- you don’t need to create one if you have no cleanup to do, but if you have one it WILL execute everytime

  10. Altogether now.. public void writeFile(String fileName) { PrintWriter out = null; try { out = new PrintWriter( new FileWriter(fileName)); for (int ind=0; ind < MAX_SIZE; ind++) { out.println(“Value at “+ind+” is “+vect.elementAt(ind));} } catch (ArrayIndexOutOfBoundsException e) { System.err.println("Caught ArrayIndexOutOfBoundsException: “ + e.getMessage()); } catch (IOException ioe) {System.out.println(“Caught IOException:”+ioe.getMessage()); } finally {if (out != null) { out.close();} }

  11. Another way: Pass the buck public void writeFile(String fileName) throws ArrayIndexOutOfBoundsException , IOException { PrintWriter out = null; try { out = new PrintWriter( new FileWriter(fileName)); for (int ind=0; ind < MAX_SIZE; ind++) { out.println(“Value at “+ind+” is “+vect.elementAt(ind));} } finally {if (out != null) { out.close();} } NOTE: You can still use the finally block exactly the same! Now code calling this method must handle the IOException. The code may optionally handle ArrayIndexOutOfBoundsException since it is a RuntimeException (unchecked). Which means this method signature is also valid: public void writeFile(String fileName) throws IOException

  12. How to throw exceptions • Your code may throw exceptions when needed using the throws keyword. This keyword takes a subclass of Throwable as an argument (Exceptions/Errors are all subclasses of Throwable) • public void addElement(int index, int[] array, int value) {if (index >= array.length) { throw new IllegalArgumentException( “Array length is:”+array.length+ ” and you attempted to add element “+index);}array[index] = value;} • Same rules apply -- if you throw a checked exception it must be caught or specified.

  13. Writing your own exceptions • You may also create your own exceptions by subclassing Exception, RuntimeException or Error. • In general you never want to subclass Error and rarely subclass RuntimeException. You usually create checked exceptions by subclassing Exception. • public MyException extends Exception { public MyException(String message) { super(message); }} • Frequently this all you want to do. Occasionally you may add more features or information to your Exceptions.

  14. Handling Exceptions • Most ways to handle exceptions depend on the exception type. However, some general debugging tips are: • Use the printStackTrace() method of exception to see where the exception occurred • Use getMessage() to show a message to the user • The best exception is one never thrown -- if you can prevent a user error that would cause an exception before it happens, do that! (For example, rather than letting the user type letters into a numeric field, watch the field and prevent letters from ever going into the field.)

More Related