Download presentation
Presentation is loading. Please wait.
Published byVera Lesmana Modified over 6 years ago
1
E x c e p t i o n s Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live. — Martin Golding Adapted from Dannelly
2
Definition An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions during the execution of a program.
3
Murach’s Java SE 6 ©2007
4
Sample Exceptions ArithmeticException ArrayStoreException
when a divide by zero is attempted ArrayStoreException trying to put an int into a float array IndexOutOfBoundsException accessing invalid array or string element ArrayIndexOutOfBoundsException subclass of IndexOutofBoundsException accessing invalid array element NegativeArraySizeException obvious NullPointerException when you try to dereference a null object reference
5
Part of the Exception Class Hierarchy
Throwable Error Exception ClassNotFoundException InstantiationException IOException FileNotFoundException EOFException RuntimeException ArithmeticException ClassCastException IllegalArgumentException IllegalThreadStateException NumberFormatException NullPointerException
6
Types of Exceptions Error Exception checked unchecked
example - OutOfMemoryError Exception checked example - FileNotFoundException unchecked example - ArrayIndexOutOfBoundsException "checked" must be handled "unchecked" are usually not dealt with directly all "errors" are "unchecked" The Error class, like the Exception class, is derived from the Throwable class. However, the Error class identifies internal errors that are rare and can’t usually be recovered from. Checked exceptions are checked by the compiler. So you must supply code that handles any checked exceptions or your program won’t compile. Unchecked exceptions are not checked by the compiler, but you can still write code that handles them. If you don’t, any unchecked exceptions will cause your program to terminate.
7
How Exceptions are Propagated
When a statement produces an exception (checked or unchecked) and the statement is not inside a try statement, then the exception is thrown up to whoever called this piece of code. If that calling function does not catch the exception, the exception is passed up to whoever called this function. etc etc etc If main throws an exception, then the JVM prints the calling stack and exits the program.
8
The throws Statement "Checked" exceptions must be dealt with. If a statement can produce a checked exception that statement must either be inside a try statement or the method must pass the possible exception up to the calling method via throws. public static void main(String[] args) throws IOException { code for reading or writing that is not inside a try statement } Go to 15
9
Catching Exceptions try { code that might throw an exception }
catch (ExceptionName param) code used when this error occurs catch (AnotherExceptionName param) { yadda yadda } finally do this code, no matter if error occurs
10
Example 1 - File Opening // open the data file for reading try {
FileReader freader = new FileReader(fname); inputFile = new BufferedReader(freader); } catch (FileNotFoundException e) System.out.println("Unknown File: " + fname); return; catch (IOException e) System.out.println("Error Opening " + fname); Note: the order of these two exceptions is important
11
Example 2.1 - Converting String to Integer
Version One - Crashes on Bad Input // read until eof and sum the values dataline = inputFile.readLine(); while (dataline != null) { nextint = Integer.parseInt(dataline); sum += nextint; }
12
Example 2.2 - Converting String to Integer
Version Two - Sum is Wrong // read until eof and sum the values dataline = inputFile.readLine(); while (dataline != null) { try nextint = Integer.parseInt(dataline); } catch (NumberFormatException nfe) System.out.println("unable to ... sum += nextint;
13
Example 2.3 - Converting String to Integer
Version Three - Infinite Loop // read until eof and sum the values dataline = inputFile.readLine(); while (dataline != null) { try nextint = Integer.parseInt(dataline); sum += nextint; } catch (NumberFormatException nfe) System.out.println("unable to ...
14
Example 2.4 - Converting String to Integer
// read until eof and sum the values dataline = inputFile.readLine(); while (dataline != null) { try nextint = Integer.parseInt(dataline); sum += nextint; } catch (NumberFormatException nfe) System.out.println("unable to convert \"" + nfe.getMessage() + "\" into an integer");
15
Creating Your Own Exceptions
Suppose you are writing a stack class. Then you will want to create your own exceptions. StackClassException StackOverflowException StackUnderflowException StackTypeMismatchException Which existing exception class do you build your exception off of? best idea is to use Exception RuntimeException is easy, but not desired
16
Example - new checked exception
declaration of your stack class: public class StackClass { public class StackClassException extends Exception; { } public class StackOverflowException extends StackClassException; { } ... inside a method that uses your stack class: try mystack.push(8); } catch (StackOverflowException e) code not complete
17
Example - declaration details
class StackException extends Exception { StackException () super (); } StackException ( String description ) super ( description ) "super" = use my mom's constructor By convention, each exception class should contain a default constructor that doesn’t accept any arguments and another constructor that accepts a string argument.
18
How to throw an exception
public class StackClass { ... // the pop method public int pop () if (stacksize == 0) throw StackUnderflowException; return list [ --stacksize ]; }
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.