Download presentation
Presentation is loading. Please wait.
Published byΜελέτη Λύκος Modified over 5 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
2
Outline for Today What is an Exception? How to Catch Exceptions
checked v. unchecked How to Catch Exceptions examples of good and bad try-catch code Creating your own types of Exception declaring your new exception throwing your new exception
3
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.
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"
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 produced 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 }
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. StackException StackOverflowException StackUnderflowException StackTypeMismatchException Which existing exception class do you build your exception off of? best idea is to use Exception RuntimeException is okay
16
Example - new checked exception
declaration of your stack class: public class StackClass { public class StackException extends Exception; {...} public class StackOverflowException extends StackException; {...} public int pop() {...} inside a method that uses your stack class: try mystack.push(8); } catch (StackOverflowException e) see code on next slide
17
Example - declaration details
public class StackException extends Exception { StackException () super (); } StackException ( String description ) super ( description ) "super" = use my mom's constructor
18
How to throw an exception
public class StackClass { ... // the pop method public int pop () if (stacksize == 0) throw StackUnderflowException; return list [ --stacksize ]; }
19
Next Classes writing classes writing classes that extend other classes
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.