Java Programming Exceptions CSC 444 By Ralph B. Bisland, Jr. Title Slid Java Programming Exceptions By Ralph B. Bisland, Jr. Drawing shadowed boxes with PowerPoint is easy. Simply use the Rectangle tool to draw the box and then choose Shadowed from the Draw menu. Be sure to delete this word processing box before using this template for your own presentation.
Exceptions A robust program deals gracefully with unexpected situations/conditions. Exceptions are unusual conditions that could arise when code is executing. The exception could make the continuation of the execution of the program impossible or undesirable. Examples of exceptions include: Divide by zero Arithmetic overflow index out of bounds
Exceptions (ctd) In Java terminology, exceptions are “thrown”. Exceptions may be system defined or user defined. Exceptions may be thrown by the system of by the programmer. Exception are “caught” with exception handlers - which is code that executes if the exception occurs. If no handler is written for the exception, the program terminates execution.
Exceptions (ctd) There are 20+ subclasses of Exceptions which are defined in the package java.lang.Throwable
Exception Hierarchy Object Throwable Error Exception RunTimeException
Exception Explanations Throwable: Superclass for all error handling. This class should not be used directly to describe a particular exception. Error: Indicates a severe problem from which recovery is difficult, if not impossible. Example: Running out of memory. It is probably best to report the error, then terminate execution of the program.
Exception Explanations (ctd) Exception: Super class for RunTimeExceptions. RunTimeException: Indicates a design or implementation problem. Example: IndexOutOfBoundsException. An attempt should probably be made to fix this type exception and continue execution of the program.
Partial Exception Hierarchy Object Throwable Exception RuntimeException ArithmeticException ArrayStoreException ClassCastException IllegalArgumentException NumberFormatException IllegalMonitorStateException IndexOutOfBoundsException ArrayIndexOutOfBoundsException StringIndexOurOfboundsException NegativeArraysizeException NullPointer Exception SecurityException
Checked Exceptions An exception to can be analyzed by the compiler. A checked exception must either be handled in the method or declared in the method signature via the throws clause. Example: IOException Designed to reduce the number of errors that could occur in program execution.
Unchecked Exceptions A subclass of RuntimeExceptions. These exceptions are not checked by the compiler because they would be difficult to check at compile time. Examples: ArithmeticException and NullPointerException.
Try-Catch To handle exceptions any block of code in which the exception could possible occur must be preceded by the “try” statement. If present the catch block(s) must lie directly below its try block. There may be multiple catch blocks, each catching a separate exception. Once the code in the exception handler is executed, control leaves the block.
Example try { some java code that could cause an exception to be thrown } catch (exception-type identifier) { code to handle the exception
A More Specific Example int x =; try { x = SimpleInput.readInt(); } Catch (NumberFormatException nfe) System.out.println (“You entered an illegal integer value”); Note: When this error occurs, the file pointer Does not move and the value currently stored In the variable ‘x” does not change.
Another Example class TestException {public static void main (String[] args) {String greetings [] = {“Hello there, I‘m Yogi Bear”, “Hi Boo-Boo”, “Welcome to Jellystone Park”}; for (int i = 0; i<= 3; i++) System.out.println (greetings[i]); }
Output orca% javac TestExc.java orca% java TestExc Hello there, I'm Yogi Bear Hi Boo-Boo Welcome to Jellystone Park java.lang.ArrayIndexOutOfBoundsException at TestExc.main(TestExc.java:8) orca%
Displaying Exceptions A method called toString can be used to convert the exception to text for display. Example: catch (Exception e) {system.out.println (e.toString);}
With Exceptions class TestException {public static void main (String[] args) {String greetings [] = {“Hello there, I‘m Yogi Bear”, “Hi Boo-Boo”, “Welcome to Jellystone Park”}; for (int i = 0; i<= 3; i++) try{System.out.println (greetings[i]);} catch (Exception e) {System.out.println(e.toString());} }
Output orca% javac TestExc1.java orca% java TestExc1 Hello there, I'm Yogi Bear Hi Boo-Boo Welcome to Jellystone Park java.lang.ArrayIndexOutOfBoundsException orca%
The exit() Method The exit() method is used to terminate execution of a Java program. An integer value must be “passed” to the exit method. This value is displayed as output so if there is more than one “exit” point, the programmer will know which exit caused termination of the program. Example: exit(0);
Unhandled Exceptions If the exception is not handled in the current block, control is transferred to the next outermost block when it may be handled. This process is called propogation of exceptions. If the exception eventually gets to the outermost block and is still not handled, execution of the program terminates,
Example Because there is no exception handler in the public static int processInput (……) { int x; . . . x = SimpleInput.readInt(); // Normal processing continues } Because there is no exception handler in the Block control is passed to the next outermost block. Problem: No value returned by the method.
Editing Input … boolean inputReadOK = false; While (!inputReadOK) try{ x = processInput (…); } catch (NumberFormatException e) {System.out.println (e); SimpleInput.readLine();// Move the file ptr System.out.println(“Input error try again”); inputReadOK = true; // normal processing continues here
A Complete Example import java.lang.*; import SimpleIO.*; class TestException {public static void main (String [] args) {int aNumber; boolean success = false; String inputString = “”; System.out.print (“Enter an integer: “); while (!success) { try { aNumber = SimpleInput.readInt(); success = true;} catch (NumberFormatException e) {inputString = SimpleInput.readString(); System.out.println (“The string: “ + inputString + “is not an integer” + “-- try again”);} } System.out.println (“You entered the integer value: “ + aNumber);
Catching Multiple Exceptions Multiple exceptions can be caught by including multiple catch blocks after the try block. Example: try{ } catch (exception1 e1) {code for this exception} catch (exception2 e2) {code for this exception}
The Finally Clause The finally clause associated with a try block ensures that a set of code will be executed whether the exception is thrown or not. The code in the finally block is usually referred to as ‘clean up” code. It is often used to do things like close files, write out final messages, etc.
Example Class FinallyTest {public static int aMethod (. . .) {. . . try { . . . } catch (IOException e) { . . .} . . . catch (EOFException e) { . . .} finally { . . . } } public static void main (String[] args { . . . }
Another Example class TestException {public static void main (String[] args) {String greetings [] = {“Hello there, I‘m Yogi Bear”, “Hi Boo-Boo”, “Welcome to Jellystone Park”}; for (int i = 0; i<= 3; i++) try{System.out.println (greetings[i]);} catch (Exception e) {System.out.println(e.toString());} finally {System.out.print (“Always displayed”);} } }
Output orca% javac TestExc2.java orca% java TestExc2 Hello there, I'm Yogi Bear Always displayed Hi Boo-Boo Welcome to Jellystone Park java.lang.ArrayIndexOutOfBoundsException orca%