Loading…

Flash Player 9 (or above) is needed to view presentations.
We have detected that you do not have it on your computer. To install it, go here.

Like this presentation? Why not share!

Itp 120 Chapt 18 2009 Exceptions & Assertions

on

  • 2,358 views

 

Statistics

Views

Total Views
2,358
Views on SlideShare
2,355
Embed Views
3

Actions

Likes
1
Downloads
134
Comments
1

1 Embed 3

http://www.slideshare.net 3

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
  • It's good presentatiion
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Itp 120 Chapt 18 2009 Exceptions & Assertions Itp 120 Chapt 18 2009 Exceptions & Assertions Presentation Transcript

  • Chapter 18 Exceptions & Assertions Java I ITP 120
  • Chapter Objectives
    • Understand the concept of exception handling
    • Become familiar with exception types
    • Learn how to use the try-catch block to handle exceptions
    • Learn how to throw exceptions
    • Understand the finally block
    • Learn how to create and use custom exceptions
    • Look at the Sum of Digits (Exercise 5.2) program with exceptions
      • See handout for students
  • Categories of Errors There are three categories or types of errors: (1) Syntax errors (2) Logic errors (sometimes called: semantic errors)‏ (3) Runtime errors Syntax errors arise because the rules of the language have not been followed. They are detected by the compiler. Logic errors occur when a program doesn't perform the way it was intended to. Runtime errors occur while the program is running if the environment detects an operation that is impossible to carry out. View slide
  • Runtime Errors View slide
  • Catching Runtime Errors
  • Catching Runtime Errors (Another example)‏
  • Exception Handling : Exceptions vs Errors
    • An exception is an object that defines an unusual or erroneous situation
    • An exception is thrown by a program or the run-time environment and can be caught and handled if desired.
    • The DIFFERENCE between an ERROR and an EXCEPTION:
    • An error is similar to an exception except that an error generally represents an unrecoverable situation and cannot be caught.
  • Exception Handling : Examples of Problems
    • Examples of situations that cause exceptions to be thrown:
    • (1) Attempting to divide by zero: x = 126.57 / 0.0
    • (2) An array index is out of bounds
    • (3) A specified file could not be found
    • (4) An I/O operation could not be completed normally
    • (5) An attempt was made to follow a null reference (to an object)‏
  • Exception Handling : Dealing with Problems
    • A Java program can be designed to:
    • (1) Not handle the exception at all.
    • (2) Handle the exception where it occurs. OR:
    • (3) Handle the exception at another place in the program.
  • Exception Handling
    • Exception handling is generally used to handle abnormal events in a program.
    • When a method encounters a problem that disrupts the normal flow, it can cause the program to CRASH !
    • But with exception handling, the method can throw an exception which informs the caller that a problem occurred allowing the caller to perform alternative actions.
    • Exception handling enables more robust programming by providing ways of recovering from errors or problems.
  • Exceptions 2 types: Checked vs Unchecked
    • Exception handling streamlines error handling by allowing your program to define a block of code, called an exception handler that is executed automatically when an error occurs.
    • Java defines standard exceptions for common errors such as divide-by-zero and file-not-found . (these are Unchecked exceptions and beyond the control of the programmer)
    • Checked exceptions CAN be handled in Java programs.
    • To respond to these errors, your program must watch for and handle these exceptions.
  • Exceptions and Exception Types
  • System Errors (Note: click the mouse to see fly-ins)‏ System errors are thrown by JVM and represented in the Error class. The Error class describes internal system errors. Such errors rarely occur. If one does, there is little you can do beyond notifying the user and trying to terminate the program gracefully.
  • Exceptions (Note: click the mouse to see fly-ins)‏ Exceptions are represented in the Exception class that describes errors caused by your program and external circumstances. These errors can be caught and handled by your program.
  • Runtime Exceptions (Note: click the mouse to see fly-ins)‏ Runtime exceptions are represented in the RuntimeException class that describes programming errors, such as bad casting, accessing an out-of-bounds array, and numeric errors.
  • Java’s Built-in UnChecked Exceptions Exception Meaning ArithmeticException Arithmetic error; divide-by-zero ArrayIndexOutOfBoundsException Array index is out of bounds ArrayStoreException Assignment of an array element is an incompatible type. ClassCastException Invalid cast operation IllegalArgumentException Illegal argument used to invoke a method IndexOutOfBoundsException Some type of index is out of bounds
  • Java’s Built-in UnChecked Exceptions Exception Meaning NegativeArraySizeException Array created with a negative size NullPointerException Invalid use of a null reference NumberFormatException Invalid conversion of a string to a numeric format StringIndexOutOfBounds Attempt to index outside the bounds of a string
  • Java’s Built-in Checked Exceptions Exception Meaning ClassNotFoundException Class not found. CloneNotSupportedException Attempt to clone an object that does not implement the Cloneable interface IllegalAccessException Access to a class is denied Instantiation Exception Attempt to create an object of an abstract class or interface. InterruptedException One thread has been interrupted by another thread NoSuchMethodException Method does not exist
  • Checked vs. Unchecked Exceptions RuntimeException , Error and their subclasses are known as UNCHECKED EXCEPTIONS . All other exceptions are known as CHECKED EXCEPTIONS , meaning that the compiler forces the programmer to check and deal with the exceptions.
  • Unchecked Exceptions In most cases, unchecked exceptions reflect programming logic errors that are not recoverable. For example, a NullPointerException is thrown if you access an object through a reference variable before an object is assigned to it; an IndexOutOfBoundsException is thrown if you access an element in an array outside the bounds of the array. These are the logic errors that should be corrected in the program. Unchecked exceptions can occur anywhere in the program. To avoid cumbersome overuse of try-catch blocks, Java does not mandate you to write code to catch unchecked exceptions .
  • Declaring Exceptions Every method should state the types of checked exceptions it might throw. This is known as declaring exceptions . public void myMethod()‏ throws IOException public void myMethod()‏ throws IOException, OtherException
  • Throwing Exceptions When the program detects an error, the program can create an instance of an appropriate exception type and throw it. This is known as throwing an exception . Here is an example, throw new SomeException(); SomeException ex = new SomeException(); throw ex;
  • Throwing Exceptions Example /** Set a new radius */ public void setRadius(double newRadius) throws IllegalArgumentException { if (newRadius >= 0)‏ radius = newRadius; else throw new IllegalArgumentException( "Radius cannot be negative"); }
  • Catching Exceptions try { statements; // Statements that may throw exceptions } catch (Exception1 exVar1) { handler for exception1; } catch (Exception2 exVar2) { handler for exception2; } ... catch (ExceptionN exVar3) { handler for exceptionN; }
  • Catching Exceptions
  • Catching Exceptions
    • Consider the scenario on the previous graphic slide:
    • Suppose an exception occurs in the try-catch block that contains a call to
    • method3 .
    • If the exception type is Exception3 , it is caught by the catch clause for handling ex3 in Method 2
    • If the exception type is Exception2 , it is caught by the catch clause for handling ex2 in Method 1
    • If the exception type is Exception1 , it is caught by the catch clause for handling ex1 in the main method.
    • If the exception type is NOT Exception1 , Exception2 , or Exception3 , the program terminates.
  • Catching Exceptions: Previous slide
    • Still referring to the scenario on the previous graphic slide:
    • If the exception type is Exception3 , then statement 5 is skipped.
    • If the exception type is Exception2 , then statements 3 & 5 are
    • skipped.
    • If the exception type is Exception1 , then statements 1,3 & 5 are skipped.
  • Catching Exceptions in Graphics Programs
    • Note:
    • An exception is ignored when …
    • an exception of a subclass of class Exception occurs in a graphics
    • program, Java prints the error message on the monitor, but the program
    • goes back to its GUI processing loop to run continuously .
  • Catch or Declare Checked Exceptions Java forces you to deal with checked exceptions. If a method declares a checked exception (i.e., an exception other than Error or RuntimeException ), you must invoke it in a try-catch block or declare to throw the exception in the calling method. For example, suppose that method p1 invokes method p2 and p2 may throw a checked exception (e.g., IOException ), you have to write the code as shown in figure (a) OR figure (b).
  • Trace a Program Execution animation try { statements; } catch(TheException ex) { handling ex; } finally { finalStatements; } Next statement; Suppose no exceptions in the statements
  • Trace a Program Execution animation try { statements; } catch(TheException ex) { handling ex; } finally { finalStatements; } Next statement; The final block is always executed
  • Trace Execution animation try { statements; } catch(TheException ex) { handling ex; } finally { finalStatements; } Next statement; Next statement in the method is executed
  • Trace a Program Execution animation try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } finally { finalStatements; } Next statement; Suppose an exception of type Exception1 is thrown in statement2
  • Trace a Program Execution animation try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } finally { finalStatements; } Next statement; The exception is handled here
  • Trace a Program Execution animation try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } finally { finalStatements; } Next statement; The final block statements are always executed.
  • Trace a Program Execution animation try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } finally { finalStatements; } Next statement; The next statement in the method in the program is now executed.
  • Trace a Program Execution animation try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } catch(Exception2 ex) { handling ex; throw ex; } finally { finalStatements; } Next statement; statement2 throws an exception of type Exception2.
  • Trace a Program Execution animation try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } catch(Exception2 ex) { handling ex; throw ex; } finally { finalStatements; } Next statement; Handle the exception
  • Trace a Program Execution animation try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } catch(Exception2 ex) { handling ex; throw ex; } finally { finalStatements; } Next statement; Execute the finally block statements
  • Trace a Program Execution animation try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } catch(Exception2 ex) { handling ex; throw ex; } finally { finalStatements; } Next statement; Rethrow the exception and control is transferred to the calling statement in the method
  • Claiming & Throwing Exceptions
    • Claiming an Exception (“throws”)‏
    • Every method must state the types of exceptions it can encounter.
    • The term claiming an exception tells the compiler what can go wrong.
    • public void someMethod( ) throws IOException
    • Throwing an Exception (“throw”)‏
    • When a program statement causes an error, the method containing he statement creates an exception object and passes it on to the system.
    • The exception object contains information about the exception including the exception type and the state of the program when the error occurred.
    • The Java code that handles the error is the exception handler.
  • GUI Calculator Code Fragment public void calculator(int operator){ //Using try -catch block for improperly formatted input. try { double num1 = new Double(jtfNumber1.getText().trim()).doubleValue(); double num2 = new Double(jtfNumber2.getText().trim()).doubleValue(); double result = 0.0; switch (operator) { case 0 : result = (num1 + num2); break; case 1 : result = (num1 - num2); break; case 2 : result = (num1 * num2); break; case 3 : result = (num1 * 1.0 / num2); break; } String str = String.format("%1.4f", result); jtfResult.setText(String.valueOf(str)); // Process improperly formatted input. } catch (NumberFormatException numberError){ JOptionPane.showMessageDialog(this, "You must enter two values", "Invalid Number Format", JOptionPane.ERROR_MESSAGE ); clearFields(); } }//End of calculate-method.
  • The JVM handles a Divide Exception ! // ExcDemoInfinity.java import javax.swing.JOptionPane; public class ExcDemoInfinity { public static void main(String args[]) { double result; String output = ""; result = 1234.56 / 0.0; // Try to divide by zero try { System.out.println( result ); // Just the word "Infinity" is printed } catch (Exception ex)‏ { System.out.println("Exception message is never printed" + ex.getMessage()); } System.out.println("End of program"); output = "The word "Infinity" is printed" + " " + "Exception was handled by the JVM"; JOptionPane.showMessageDialog(null,output); } // End of main method } // End of class ExcDemoInfinity
  • Claiming & Throwing Exceptions
    • Catching an Exception
    • This is the process of finding an exception handler.
    • The exception handler must match the type of exception thrown.
    • ( see demo program ExcTypeMismatch.java )‏
    • If no matching handler is found, the program terminates .
  • Claiming & Throwing Exceptions: throws & throw
    • Use the keyword throws to claim an exception.
    • Example:
    • public void myDivideMethod ( double d1, double d2 )
    • throws RunTimeException
    • Use the keyword throw to throw an exception
    • Example:
    • if( checkAmount > availableBalance) throw new
    • InsufficientFundsException( );
  • Throwing Exceptions
    • In the method that has claimed the exception, you can throw an object of the exception if the exception arises.
    • The following is the syntax to throw an exception :
    • throw new MyException ( );
    • Or:
    • MyException myEx = new MyException ( );
    • throw myEx;
  • Catching, Claiming, and Throwing Exceptions
  • Some Constructors & Methods of class Throwable
    • public Throwable ( )‏
    • Default constructor
    • Creates an instance of Throwable with an empty message string
    • public Throwable (String messageString)‏
    • Constructor with parameters
    • Creates an instance of Throwable with the message string specified
    • by the parameter messageString
  • Some Constructors & Methods of class Throwable
    • public String getMessage( )‏
    • Returns the detailed message stored in the object
    • public void printStackTrace( )‏
    • Method to print the stack trace showing the sequence of method calls
    • when an exception occurs
  • Some Constructors & Methods of class Throwable
    • public void printStackTrace(PrintWriter stream )‏
    • Method to print the stack trace showing the sequence of method calls
    • when an exception occurs. Output is sent to the stream specified by
    • parameter stream.
    • public String toString( )‏
    • Returns a string representation of the Throwable object
  • The Exception Hierarchy
    • In Java, all exceptions are represented in the various classes.
    • All exception classes are derived from a class called Throwable
    • The two direct subclasses of the class Throwable are:
    • Exception and Error
    • Exceptions of type Error are related to errors that occur in the Java Virtual Machine (JVM) itself and NOT in your program.
    • Error type exceptions are BEYOND YOUR CONTROL !
    • Exceptions of type Exception are errors that result from YOUR program’s activity.
    • RunTimeException is an important subclass of subclass Exception.
  • Java’s Built-in Exceptions
    • Inside the java.lang package, Java defines several exception classes.
    • The most general of these exceptions are subclasses of the standard type RuntimeException.
    • Since java.lang is implicitly imported into all Java programs, most exceptions derived from RuntimeException are automatically available.
    • The unchecked exceptions defined in java.lang are listed on subsequent slides in this presentation.
    • Unchecked exceptions are exceptions that the compiler does NOT check to see if a method handles or throws those exceptions.
    • Checked exceptions MUST be caught and handled.
  • 2 Types of Exceptions: Checked & Unchecked
    • UNCHECKED EXCEPTIONS: (NOT checked by the compiler)‏
    • Do NOT have to be caught. (Beyond your control)‏
    • CHECKED EXCEPTIONS: (Checked by the compiler)‏
    • They MUST be caught and handled.
  • About Checked & Unchecked Exceptions… Checked Exceptions (Checked by the Java compiler)‏ Any exception that can be analyzed by the compiler is called a checked exception. For example, IOExceptions are checked exceptions. Since the methods read and readLine throw IOException, these methods throw checked exceptions. When the compiler encounters these method calls, it checks whether the program handles IOException, or reports them by throwing them. Having the compiler check for exceptions reduces the number of exceptions not properly handled by the program.
  • About Checked & Unchecked Exceptions… Unchecked exceptions are those NOT checked by the Java compiler. When a program is being compiled, it may NOT be possible for the compiler to determine if exceptions such as division-by-zero or array-index-out-of-bounds will occur. Therefore, to improve the reliability and correctness of Java programs, programmers should check for these types of exceptions.
  • Java’s Built-in UnChecked Exceptions Exception Meaning ArithmeticException Arithmetic error; divide-by-zero ArrayIndexOutOfBoundsException Array index is out of bounds ArrayStoreException Assignment of an array element is an incompatible type. ClassCastException Invalid cast operation IllegalArgumentException Illegal argument used to invoke a method IndexOutOfBoundsException Some type of index is out of bounds
  • Java’s Built-in UnChecked Exceptions Exception Meaning NegativeArraySizeException Array created with a negative size NullPointerException Invalid use of a null reference NumberFormatException Invalid conversion of a string to a numeric format StringIndexOutOfBounds Attempt to index outside the bounds of a string
  • Exceptions in GUI Applications The methods are executed on the threads. If an exception occurs on a thread, the thread is terminated if the exception is not handled. However, the other threads in the application are not affected. There are several threads running to support a GUI application. A thread is launched to execute an event handler (e.g., the actionPerformed method for the ActionEvent). If an exception occurs during the execution of a GUI event handler, the thread is terminated if the exception is not handled. Interestingly, Java prints the error message on the console, but does not terminate the application. The program goes back to its user-interface-processing loop to run continuously .
  • Example: Exceptions in GUIs
    • An error message appears on the console, but the GUI application continues running.
    • Write a program that creates a user interface to perform integer divisions. The user enters two numbers in the text fields Number 1 and Number 2. The division of Number 1 and Number 2 is displayed in the Result field when the Divide button is clicked.
  • Exceptions thrown by methods of class Integer Remember: Java programs accept only STRINGS as input. Numbers, integer or decimal, are entered as strings ! The method parseInt of the class Integer is used to convert an integer string into the equivalent integer. If the string contains any character that is not a number, the method parseInt will throw an exception: NumberFormatException (an unchecked exception)‏ Also, the method parseDouble will throw an exception if the string does not contain a valid number. double dblNumber = Double.parseDouble (inputString);
  • Java’s Built-in Checked Exceptions Exception Meaning ClassNotFoundException Class not found. CloneNotSupportedException Attempt to clone an object that does not implement the Cloneable interface IllegalAccessException Access to a class is denied Instantiation Exception Attempt to create an object of an abstract class or interface. InterruptedException One thread has been interrupted by another thread NoSuchMethodException Method does not exist
  • Exception Handling Fundamentals
    • Java exception handling is managed using five keywords:
    • try, catch, throw, throws, finally
    • Program statements that you want to monitor are contained within a try block. If an exception occurs within the try block, it is thrown .
    • Your program code can catch this exception using a catch statement and handle it in some rational manner.
    • To manually throw an exception, use the keyword throw .
    • Any code that absolutely must be executed upon exiting from a try block is put in a finally block.
  • Exception Handling Fundamentals
    • To manually throw an exception, use the keyword throw .
    • public void setRadius ( double newRadius)‏
    • throws IllegalArgumentException
    • {
    • if (newRadius >= 0)‏
    • radius = newRadius;
    • else
    • throw new IllegalArgumentException(
    • “ THE CIRCLE’S RADIUS CANNOT BE NEGATIVE !");
    • }
    • Any code that absolutely must be executed upon exiting from a try block is put in a finally block. (see next slide  )‏
  • Handling Exceptions within a Program The general syntax of the try/catch/finally block is: try { // statements that may throw exceptions } catch (ExceptionClassName1 ex1)‏ { // exception handler code statements } continued on next page 
  • Handling Exceptions within a Program (cont.)‏ catch (ExceptionClassName2 ex2)‏ { // exception handler code } … catch (ExceptionClassName3 ex3)‏ { // exception handler code } finally // The finally block is always executed ! { // finally block statements }
  • Handling Exceptions within a Program (cont.)‏ Consider the following catch block: catch ( ArithmeticException ex )‏ { System.out.println(“Error: “ + ex.getMessage( ) ); } The catch block catches an exception of type ArithmeticException which is a runtime exception. The identifier ex is an identifier is a reference variable of the type ArithmeticException.
  • Handling Exceptions within a Program (cont.)‏ If an ArithmeticException is thrown by the associated try block, the reference parameter ex contains the address of the exception thrown by the try block. The object ex stores a detailed description of the the thrown exception. The method getMessage( ) or the method t oString( ) will retrieve and print the message containing the description of the thrown exception.
  • Handling Exceptions within a Program (cont.)‏ Examples: catch ( ArithmeticException ex )‏ { // Below: Use either getMessage( ) or toString( )‏ System.out.println(“Error: “ + ex.getMessage( ) ); System.out.println(“Error: “ + ex.toString( ) ); } catch ( NumberFormatException numEx )‏ { System.out.println(“Error: “ + numEx.getMessage( ) ); }
  • Exception Handling
    • Example 18.1 This program aborts due to an attempt to divide by zero
      • public class TestException1
      • {
      • public static void main( String[ ] args )‏
      • {
      • System.out.println ( 120.5 / 0); // Division by zero
      • } // End main method
      • } // End of class TestException1
  • Exception Handling
    • Example 18.2 This program handles the divide by zero error when it occurs
      • public class TestException2 {
      • public static void main( String[ ] args ) {
      • try
      • {
      • System.out.println( 120 / 0 ); // Divide by zero attempted
      • }
      • catch( Exception ex ) // Exception is a class; ex is an object of
      • // class Exception
      • {
      • System.out.println(“Error: “ + ex.getMessage());
      • }
      • System.out.println(“Continued execution after handling the error” );
      • } // End main method
      • } // End of class TestException2
  • Exception Handling
    • Exceptions are thrown by methods
    • But … not all methods throw exceptions
    • If a method throws exceptions, it is the responsibility of the caller to handle the problems reported by the method.
    • Generally, methods throw exceptions to report problems or
    • any events (other than the expected one) to the caller of the method
  • Exceptions and Exception Types
    • There is a hierarchy of exceptions with Throwable being at the top
    • Two types of exceptions: Checked Exceptions and Unchecked Exceptions.
    • Checked Exceptions are exceptions that must be caught
    • Unchecked Exceptions do NOT have to be caught
      • Examples of unchecked exceptions:
      • RuntimeException and its subclasses such as:
      • ArithmeticException,
      • IndexOutOfBoundsException,
      • NullPointerException
  • Claiming an Exception
    • Java’s Exception handling is based on three operations
      • Claiming an exception
      • Throwing an exception
      • Catching an exception
    • Claiming an exception
      • By using the keyword throws in a method declaration to inform the compiler that the method might throw an exception
      • Example:
        • public void Amethod() throws IOException
      • A method also lets any caller know to expect IOException may be thrown
      • A method may throw more than one exception. It must include all of them in the declaration, each separated by comma
      • public void Bmethod() throws Exception1, Exception2, Exception3
  • Throwing an Exception
    • After a method declares that it might throw an exception, it is free to throw it from inside the method.
      • public void Amethod( ) throws IOException
      • {
      • // Doing some operations and something goes wrong
      • throw new IOException();
      • }
    • A method can throw more than one exception since any number of things can go wrong.
  • Catching an Exception
    • The caller of a method which throws an exception must be prepared to catch the exception by using the try-catch block.
      • try
      • {
      • Bmethod( ); // Bmethod might throw any of the exceptions caught below:
      • }
      • catch(Exception1 ex1)‏
      • {
      • // Handle the problem here
      • }
      • catch(Exception2 ex2)‏
      • {
      • // handle the problem here
      • }
      • catch(Exception3 ex3)‏
      • {
      • // Handle the problem here
      • }
  • Exception Handling
      • Example 18.3
      • public class Divide
      • {
      • private double number1;
      • private double number2;
      • Divide( ) { // Default constructor
      • number1 = 1;
      • number2 = 2; }
      • Divide( double num1, double num2) //Constructor with parameters
      • { number1 = num1;
      • number2 = num2; }
      • public double divideMethod( ) throws ArithmeticException
      • {
      • if ( number2 == 0 )
      • throw new ArithmeticException(“The denominator is zero ‘);
      • else
      • return number1 / number2; // It is safe to carry out the division.
      • }
      • }
  • Example 18.3 continued
      • public class TestDivide
      • {
      • public static void main( String[ ] args)‏
      • {
      • Divide myDivider = new Divide( 5, 3); // Create new object
      • try
      • {
      • System.out.println(myDivider.divideMethod());
      • }
      • catch(ArithmeticException ex)‏
      • {
      • System.out.println (“Error: “ + ex.getMessage() );
      • }
      • }
      • }
  • Example 18.3 continued
      • public class TestDivide
      • { // If the first statement in a “try” block causes an exception,
      • // the next statement will NOT be executed.
      • public static void main( String[ ] args)‏
      • {
      • Divide myDivider = new Divide( 21,0); // Instantiate 1 st object
      • Divide myDivider2 = new Divide (16, 4); // Instantiate 2 nd object
      • try
      • {
      • System.out.println(myDivider.divideMethod( )); // Causes divide exception
      • System.out.println(myDivider2.divideMethod( )); // Won’t be executed !
      • }
      • catch(ArithmeticException ex)‏
      • {
      • System.out.println (“Error: “ + ex.getMessage() );
      • }
      • }
      • }
  • Using try and catch
    • Keywords try and catch work together; you cannot have a try without a catch or a catch without a try. The general form of the try/catch exception follows:
    • try {
    • // (Block of code to monitor for errors)‏
    • }
    • catch (ExceptionType1 exOb) {
    • // Handler for ExceptionType1
    • }
    • catch (ExceptionType2 exOb) {
    • // Handler for ExceptionType2
    • }
  • Using try and catch
    • As the previous general form example shows, there can be more than one catch statement associated with a try.
    • The type of exception determines which catch statement is executed.
    • Only that catch statement is executed; all others are by-passed.
    • When an exception is caught, exOb will receive its value.
    • If NO exception is thrown, then the try block ends normally, and all of the catch statements are bypassed.
    • Execution then resumes with the first statement following the
    • last catch statement
    • Catch statements are executed only if an exception is thrown.
  • A Simple Exception Example class ExcDemo1 { // Demonstrate exception handling public static void main(String[ ] args) { int nums[ ] = new int[4]; // One-dimensional array of 4 integer numbers try { System.out.println("Before exception is generated."); // Generate an index out-of-bounds exception. nums[7] = 25; // Attempt to store the integer 25 into 8 th array position System.out.println("this won't be displayed"); } catch (ArrayIndexOutOfBoundsException ex) { System.out.println(“Error from Java: “ + ex.getMessage( ) ); System.out.println("Index out-of-bounds!"); } // End of catch statement System.out.println("After catch statement."); } // End of main method } // End of class ExcDemo1
  • A Simple Exception example (continued)‏ Output from running Java program ExcDemo1 Before exception is generated. Error from Java: null Index out-of-bounds! After catch statement.
  • Another Exception Example: // An exception can be generated by one method and caught by another. public class ExcTest { // See next slide  // Generate an exception. static void genException() // The offending method { int nums[ ] = new int[4]; // Declare an array of integers System.out.println("Before exception is generated."); // generate an index out-of-bounds exception nums[7] = 120; // Attempt to store 120 into the 8 th array member System.out.println(“This message won't be displayed !"); } } // End of class ExcTest An
  • Another Exception Example (continued)‏ class ExcDemo2 { public static void main(String[ ] args) { try { ExcTest . genException ( ); // Use class ExcTest (see previous slide)‏ } catch (ArrayIndexOutOfBoundsException ex) { // catch the exception System.out.println(“Exception: “ + ex.getMessage( ) ); System.out.println("Index out-of-bounds!"); // This is printed } System.out.println("After catch statement."); // This is printed } // End of main method } // End of class ExcDemo2
  • The Consequences of an Uncaught Exception
    • Catching one of Java’s standard exceptions has a benefit…
    • It prevents abnormal program termination.
    • If your program does NOT catch an exception, then it will be caught by the Java Virtual machine (JVM).
    • But… the JVM’s default exception handler terminates execution and displays a stack trace and error message.
    • In the next example, the index-out-of-bounds exception is NOT caught by the program.
  • The Consequences of an Uncaught Exception // Let JVM handle the error. class NotHandled { public static void main(String[ ] args) { int nums[ ] = new int[4]; System.out.println("Before exception is generated."); // generate an index out-of-bounds exception nums[7] = 54; // Try to assign a number to the 8 th position } // End of main method } // End of class NotHandled
  • The Consequences of an Uncaught Exception
    • In the previous program, when the array index error occurs, execution is halted, and the following error message is displayed:
    • Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException
    • at NotHandled.main (NotHandled.java:9)‏
  • Exception Type must match Type in the catch
    • The type of exception MUST match the type specified in a catch statement. If there is a mismatch, there will be an abnormal program termination.
    • In the next example, the program tries to catch an array boundary error with a catch statement for an ArithmeticException (another of Java’s built-in exceptions) When the array boundary is overrun, an ArrayIndexOutOfBoundsException is generated, but it won’t be caught by the catch statement.
    • Run the Java program ExcTypeMismatch.java to verify.
  • Exception Type must match Type in the catch
    • Exception Type must match the type in the catch
      • // This won't work!
      • class ExcTypeMismatch {
      • public static void main(String[ ] args) {
      • int [ ] nums = new int[4];
      • try {
      • System.out.println("Before exception is generated.");
      • // generate an index out-of-bounds exception
      • nums[7] = 55; // Attempt to store 55 into 8 th array position
      • System.out.println(“This won't be displayed");
      • }
  • Exception Type must match Type in the catch // Can't catch an array boundary error with an ArithmeticException. catch (ArithmeticException exc) // Incorrect exception type { // catch the exception System.out.println("Index out-of-bounds!"); // Incorrect message! } System.out.println("After catch statement."); // Not printed } // End of main method } // End of class
  • Exceptions Help You to Handle Errors Gracefully public class ExcDemo3 { // Handle errors gracefully & continue public static void main(String[ ] args) { int number[ ] = { 4, 8, 16, 32, 64, 128 }; int denom[ ] = { 2, 0, 4, 4, 0, 8 }; for(int i=0; I <number.length; i++) { try { System.out.println(number[i] + &quot; / &quot; + denom[i] + &quot; is &quot; + number[i] / denom[i]); } catch (ArithmeticException ex) { // catch the exception System.out.println(&quot;Can't divide by Zero!&quot;); } } // End of for loop } // End of main } // End of class ExcDemo3
  • Using Multiple Catch Statements
    • You can associate more than one catch statement with a try.
    • This is commonly done.
    • However, each catch statement must catch a different type of exception.
    • In the next example, the program catches two types of errors:
      • array boundary errors
      • divide-by-zero errors .
  • Using Multiple Catch Statements // Use multiple catch statements. class ExcDemo4 { public static void main(String[ ] args) { // Here, array number is longer than array denom. int number[ ] = { 4, 8, 16, 32, 64, 128, 256, 512 }; // 8 elements int denom[ ] = { 2, 0, 4, 4, 0, 8 }; // 6 elements for(int i=0; i<number.length; i++) { try { System.out.println(number[i] + &quot; / &quot; + denom[i] + &quot; is &quot; + number[i]/denom[i]); }
  • Using Multiple Catch Statements catch (ArithmeticException exc) { // catch the exception System.out.println(&quot;Cannot divide by Zero!&quot;); } catch (ArrayIndexOutOfBoundsException ex) { // catch the exception System.out.println(“Exception: “ + ex.getMessage( )); System.out.println(&quot;No matching element found.&quot;); } } // End of for loop } // End of main } // End of class ExcDemo4
  • Using Multiple Catch Statements
    • The output of the previous program ExcDemo4 is:
    • 4 / 2 is 2
    • Can’t divide by Zero!
    • 16 / 4 is 4
    • 32 / 4 is 8
    • Can’t divide by Zero!
    • 128 / 8 is 16
    • No matching element found.
    • No matching element found.
  • Catching SubClass Exceptions
    • A catch clause for a superclass will also match any of its subclasses.
    • For example, since the superclass of all exceptions is Throwable , to catch all possible exceptions, just catch Throwable !
    • If you want to catch exceptions of both a superclass type and a subclass type, put the subclass first in the catch sequence.
    • Putting the superclass first causes unreachable code to be created since the subclass catch clause can never execute the code.
    • In Java, unreachable code is an error !
  • Catching SubClass Exceptions // Subclasses must precede superclasses in catch statements. class ExcDemo5 { public static void main(String[ ] args) { // Here, array number is longer than array denom. int number[ ] = { 4, 8, 16, 32, 64, 128, 256, 512 }; int denom[ ] = { 2, 0, 4, 4, 0, 8 }; for(int i=0; i<number.length; i++) { try { System.out.println(number[i] + &quot; / &quot; + denom[i] + &quot; is &quot; + number[i] / denom[i]); }
  • Catching SubClass Exceptions catch (ArrayIndexOutOfBoundsException exc) // Subclass is first ! { System.out.println(&quot;No matching element found.&quot;); } catch (Throwable ex) // From superclass Throwable { System.out.println(&quot;Some type of exception occurred !&quot;); // Could also add: System.out.println(“Exception: “ + ex.getMessage( ) + “ occurred”); } } // End of for loop } // End of main method } // End of class ExcDemo5
  • Catching SubClass Exceptions Output from the program ExcDemo5: 4 / 2 is 2 Some exception occurred. 16 / 4 is 4 32 / 4 is 8 Some exception occurred. 128 / 8 is 16 No matching element found. No matching element found.
  • Try Blocks can be Nested
    • One try block can be nested within another. An exception generated within the inner try block that is NOT caught by a catch associated with that inner try is propagated to the outer try block .
    • In the next program example, the ArrayIndexOutOfBoundsException is NOT caught by the inner try block, but it is caught by the outer try block.
  • Try Blocks can be Nested // Use a nested try block. Catch error in outer block class NestTrys { public static void main(String[ ] args) { // Here, number array is longer than denom array int number[ ] = { 4, 8, 16, 32, 64, 128, 256, 512 }; // 8 elements int denom[ ] = { 2, 0, 4, 4, 0, 8 }; // 6 elements try { // outer try for(int i=0; I < number.length; i++) { try { // nested try Start of inner try block System.out.println(number[i] + &quot; / &quot; + denom[i] + &quot; is &quot; + number[i] / denom[i]); } // End of inner try
  • Try Blocks can be Nested catch (ArithmeticException ex) { System.out.println(&quot;Can't divide by Zero!&quot;); // Catch the exception } } // End of for loop } // End of outer try catch (ArrayIndexOutOfBoundsException exc) { // catch the exception System.out.println(&quot;No matching element found.&quot;); System.out.println(&quot;Fatal error -- program terminated.&quot;); } } // End of main method } // End of class NestTrys
  • Try Blocks can be Nested
    • In the previous program example, an exception that can be handled by the inner try , a divide-by-zero error, allows the program to continue.
    • However, an array boundary error is caught by the outer try which causes the program to terminate.
    • Output from the previous program example is :
    • 4 / 2 is 2
    • Can’t divide by Zero!
    • 16 / 4 is 4
    • 32 / 4 is 8
    • Can’t divide by Zero!
    • 128 / 8 is 16
    • No matching element found.
    • Fatal error – program terminated. < --------- Note
  • Throwing an Exception Manually
    • The previous examples have been catching exceptions generated automatically by the Java Virtual Machine (JVM)‏
    • However, it is possible to manually throw an exception by using the throw statement. The general form of the throw statement is:
    • throw exceptOb ;
    • exceptOb must be an object of class Exception which is derived from class Throwable (which is derived from class Object )‏
  • Throwing an Exception Manually // Manually throw an exception. class ThrowDemo { public static void main(String[ ] args) { try { System.out.println(&quot;Before throw.&quot;); throw new ArithmeticException( ); } catch (ArithmeticException exc) { // catch the exception System.out.println(&quot;Exception caught.&quot;); } System.out.println(&quot;After try/catch block.&quot;); } // End of main method } // End of class ThrowDemo
  • Throwing an Exception Manually
    • Output from the previous program ThrowDemo:
    • Before throw.
    • Exception caught.
    • After try/catch block.
  • Rethrowing an Exception
    • An exception caught by one catch statement can be rethrown so that it can be caught by an outer catch statement.
    • The reason for rethrowing an exception is to allow multiple handlers access to the exception.
    • When you rethrow an exception, it will NOT be recaught by the same catch statement, but it will propagate to the next catch statement.
  • Rethrowing an Exception // Rethrow an exception. class Rethrow { public static void genException( ) { // Note: array numer is longer than array denom int numer[ ] = { 4, 8, 16, 32, 64, 128, 256, 512 }; int denom[ ] = { 2, 0, 4, 4, 0, 8 }; for(int i=0; i<numer.length; i++) { try { System.out.println(numer[i] + &quot; / &quot; + denom[i] + &quot; is &quot; + numer[i]/denom[i]); }
  • Rethrowing an Exception } catch (ArithmeticException exc) { // catch the exception System.out.println(&quot;Can't divide by Zero!&quot;); } catch (ArrayIndexOutOfBoundsException exc) { // catch the exception System.out.println(&quot;No matching element found.&quot;); throw exc; // Rethrow the exception ! } } }
  • Rethrowing an Exception public class RethrowDemo { public static void main(String[ ] args) { try { Rethrow.genException(); // Class Rethrow, method genException()‏ } catch (ArrayIndexOutOfBoundsException exc) { // recatch exception System.out.println(&quot;Fatal error: program terminated.&quot;); } } // End of main method } // End of class RethrowDemo
  • Rethrowing an Exception
    • In the previous program, divide-by-zero errors are handled locally by the genException( ) method, but an array boundary error is rethrown.
    • The array boundary error is caught by the main( ) method
    • Output from the program RethrowDemo.java:
    • 4 / 2 is 2
    • Can’t divide by zero !
    • 16 / 4 is 4
    • 32 / 4 is 8
    • Can’t divide by zero !
    • 128 / 8 is 16
    • No matching element found
    • Fatal error – program terminated
  • Using the keyword finally
    • Sometimes you will want to define a block of code that will execute when the program leaves a try/catch block.
    • For example, an exception might cause an error that terminates the current method, causing its premature return.
    • However, that method may have opened a file or a network connection that needs to be closed.
    • Java has a way to handle them: finally
    • To specify that a block of code to execute when a try/catch block is exited, include a finally block at the end of the try/catch sequence.
  • Using the keyword finally
    • General form of a try/catch that includes finally :
    • try
    • { // Block of code to monitor for errors… }
    • catch (ExcepType1 exObj1)
    • { // Handler for ExceptionType1 }
    • catch (ExcepType2 exObj2)
    • { // Handler for ExceptionType2 }
    • finally { // finally code goes here … }
  • Using the keyword finally
    • A try – catch block can be structured as try-catch-finally
      • try
      • { ………. }
      • catch ( Exception ex )
      • { ………… }
      • finally { ………… }
    • finally indicates that after you finish handling the exception, perform these last actions. Or, even if the exception was not thrown or handled, perform the actions anyway .
  • Using the keyword finally
    • The finally block will be executed whenever execution leaves a
    • try/catch block, no matter what conditions cause it.
    • The last code to be executed is the code in the finally block
  • Using the keyword finally public class UseFinally { // Use finally public static void genException(int num) { int t; int nums[ ] = new int[20]; // 20 numbers in array “nums” System.out.println(&quot;Receiving &quot; + num ); try { switch(num) { case 0: t = 10 / num; // Generate divide-by-zero error (num is zero)‏ break; case 1: nums[25] = 445; // Generate array index of out bounds error. break; case 2: return; // return from try block } } }
  • Using the keyword finally catch (ArithmeticException exc) { // catch the exception System.out.println(&quot;Can't divide by Zero!&quot;); return; // return from catch } catch (ArrayIndexOutOfBoundsException exc) { // catch the exception System.out.println(&quot;No matching element found.&quot;); } finally { System.out.println(“In finally block Leaving try.&quot;); } } // End of method genException()‏ } // End of class UseFinally
  • Using the keyword finally
    • Output from the previous program: UseFinally.java
    • Receiving 0
    • Can’t divide by Zero!
    • Leaving try. (message from finally block)‏
    • Receiving 1
    • No matching element found.
    • Leaving try. (message from finally block)‏
    • Receiving 2 (merely return from try block)‏
    • In finally block Leaving try. ( message from finally block)‏
  • Using Keyword throws
    • In some cases, if a method generates an exception that is does not handle, it must declare the exception in a throws clause.
    • The general form of a method that includes a throws clause is:
    • return-type methodName(parameter list) throws exception-list
    • { // body of the method here }
    • Here , exception-list is a comma-separated list of exceptions that
    • the method might throw outside of itself.
    • Example:
    • public void someMethod() throws Exception1, Exception2, Exception3
  • Using Keyword throws
    • In preceding examples, you did not need to specify a throws clause because exceptions that are subclasses of Error or RuntimeException do NOT need to be specified in a throws list.
    • Java simply assumes that a method may throw one.
    • All other types of exceptions must be declared.
    • When performing keyboard input , you should add the clause:
    • throws java.io.IOException to the main( ) method.
  • Creating Custom Exceptions
    • The usefulness of exceptions really stems from programs being able to report any type of problem encountered.
    • Custom exceptions can be created by inheriting from any Exception class.
    • For example we can create an exception to report insufficient funds when we try to withdraw too much money from an account.
  • Creating Custom Exceptions
    • Example 18.4 Insufficient Funds Exception (Custom Exception)‏
      • public class InsufficientFundsException extends Exception( )‏
      • {
      • public InsufficientFundsException( ) // Default constructor
      • {
      • super( “Insufficient funds to complete transaction” );
      • }
      • public InsufficientFundsException( String message )‏
      • {
      • super( message ); // Constructor with message parameter
      • }
      • }
  • Creating Custom Exceptions
    • Example 18.4 Continued
      • // Account class
      • public class Account {
      • // include data members of Account class here
      • // include constructors here
      • // include other methods except withdraw which might throw exceptions
      • // Next line of code: claiming an exception (throws)‏
      • public void withDraw( double amount ) throws InsufficientFundsException( )‏
      • { // Next line of code: throwing an exception (throw)‏
      • if ( amount > balance ) throw new InsufficientFundsException( );
      • else
      • balance = balance – amount;
      • } // End of method withDraw
      • } // End of class Account
  • Creating Custom Exceptions
    • Note that the withdraw method of Account class in Example 18.4 has declared that it might throw an exception
      • Note the difference between the keywords throw and throws
    • Any call to the withdraw method must be enclosed in a try-catch block
      • Because the caller must be ready to handle the exception if it is thrown.
  • Refresher: throw & throws
    • Claiming an Exception (“throws”)‏
    • Every method must state the types of exceptions it can encounter.
    • The term claiming an exception tells the compiler what can go wrong.
    • public void someMethod( ) throws IOException
    • Throwing an Exception (“throw”)‏
    • When a program statement causes an error, the method containing he statement creates an exception object and passes it on to the system.
    • The exception object contains information about the exception including the exception type and the state of the program when the error occurred.
    • The Java code that handles the error is the exception handler.
  • Creating Custom Exceptions
    • Here is another example of a custom exception which is named
    • NonIntResultException.
    • NonIntResultException which is generated when the result of dividing two integer values produces a result with a fractional component.
    • The method toString( ) is overridden which allows the description of the exception to be displayed using the println( ) method
    • See the next slide 
  • Creating Custom Exceptions // Create and use a custom exception. class NonIntResultException extends Exception { int n; int d; NonIntResultException(int i, int j) // Constructor with parameters { n = i; d = j; }
  • Creating Custom Exceptions public String toString( ) { return &quot;Result of &quot; + n + &quot; / &quot; + d + &quot; is non-integer.&quot;; } } // End of class NonIntResultException
  • Creating Custom Exceptions class CustomExceptDemo { public static void main(String[ ] args) { // array numer has some odd values which yield non integer results // when dividing one integer by another. int numer [ ] = { 4, 8, 15, 32, 64, 127, 256, 512 }; int denom[ ] = { 2, 0, 4, 4, 0, 8 };
  • Creating Custom Exceptions for(int i=0; I < numer.length; i++) { try { if( (numer[i] % 2) != 0) throw new NonIntResultException(numer[i], denom[i]); System.out.println(numer[i] + &quot; / &quot; + denom[i] + &quot; is &quot; + numer[i]/denom[i]); }
  • Creating Custom Exceptions catch (ArithmeticException exc) { // catch the exception System.out.println(&quot;Can't divide by Zero!&quot;); } catch (ArrayIndexOutOfBoundsException exc) { // catch the exception System.out.println(&quot;No matching element found.&quot;); } catch (NonIntResultException ex) { System.out.println( “Exception: “ + ex.getMessage( )); } } // End of for loop } // End of main method } // End of class CustomExceptDemo
  • Creating Custom Exceptions The output from the previous program is: 4 / 2 is 2 Can’t divide by Zero! Result of 15 / 4 is non-integer. 32 / 4 is 8 Can’t divide by Zero! Result of 127 / 8 is non-integer. No matching element found. No matching element found.
  • Cautions When Using Exceptions !
    • Exception handling separates error-handling code from normal programming tasks, thus making programs easier to read and to modify .
    • But, exception handling usually requires more time and resources because it requires instantiating a new exception object , rolling back the call stack , and propagating the errors to the calling methods.
  • Assertions [ Optional ] The following section on Assertions is OPTIONAL
  • Assertions [ Optional ] An assertion is a Java statement that enables you to assert an assumption about your program. An assertion contains a Boolean expression that should be true during program execution. Assertions can be used to assure program correctness and avoid logic errors.
  • Declaring Assertions An assertion is declared using the new Java keyword assert in JDK 1.4 as follows: assert assertion ; or assert assertion : detailMessage ; where a ssert ion is a Boolean expression and detailMessage is a primitive-type or an Object value.
  • Executing Assertions When an assertion statement is executed, Java evaluates the assertion. If it is false, an AssertionError will be thrown. The AssertionError class has a no-arg constructor and seven overloaded single-argument constructors of type int, long, float, double, boolean, char, and Object. For the first assert statement with no detail message, the no-arg constructor of AssertionError is used. For the second assert statement with a detail message, an appropriate AssertionError constructor is used to match the data type of the message. Since AssertionError is a subclass of Error, when an assertion becomes false, the program displays a message on the console and exits.
  • Executing Assertions Example public class AssertionDemo { public static void main(String[] args) { int i; int sum = 0; for (i = 0; i < 10; i++) { sum += i; } assert i == 10; assert sum > 10 && sum < 5 * 10 : &quot;sum is &quot; + sum; } }
  • Compiling Programs with Assertions Since assert is a new Java keyword introduced in JDK 1.4, you have to compile the program using a JDK 1.4 compiler. Furthermore, you need to include the switch –source 1.4 in the compiler command as follows: javac –source 1.4 AssertionDemo.java NOTE: If you use JDK 1.5, there is no need to use the –source 1.4 option in the command.
  • Running Programs with Assertions By default, the assertions are disabled at runtime. To enable it, use the switch –enableassertions , or –ea for short, as follows: java –ea AssertionDemo Assertions can be selectively enabled or disabled at class level or package level. The disable switch is –disableassertions or –da for short. For example, the following command enables assertions in package package1 and disables assertions in class Class1 . java –ea:package1 –da:Class1 AssertionDemo
  • Using Exception Handling or Assertions Assertion should not be used to replace exception handling. Exception handling deals with unusual circumstances during program execution. Assertions are to assure the correctness of the program. Exception handling addresses robustness and assertion addresses correctness. Like exception handling, assertions are not used for normal tests, but for internal consistency and validity checks. Assertions are checked at runtime and can be turned on or off at startup time.
  • Using Exception Handling or Assertions, cont. Do not use assertions for argument checking in public methods . Valid arguments that may be passed to a public method are considered to be part of the method’s contract. The contract must always be obeyed whether assertions are enabled or disabled. For example, the following code should be rewritten using exception handling as shown in Lines 28-35 in Circle.java in Listing 18.1. public void setRadius(double newRadius) { assert newRadius >= 0; radius = newRadius; }
  • Using Exception Handling or Assertions, cont. Use assertions to reaffirm assumptions . This gives you more confidence to assure correctness of the program. A common use of assertions is to replace assumptions with assertions in the code.
  • Using Exception Handling or Assertions, cont. Another good use of assertions is place assertions in a switch statement without a default case. For example, switch (month) { case 1: ... ; break; case 2: ... ; break; ... case 12: ... ; break; default: assert false : &quot;Invalid month: &quot; + month }
  • Chapter 17 Demo Programs Exceptions ExcDemo1.java ExcDemo3.java ExcDemo4.java ExcDemo5.java ExcTypeMismatch.java TestCircleWithException.java ExceptionScope.java goes with (CircleWithException.java)‏ ExcCustomExceptDemo.java ExcDemoInfinity.java ExcNestedTrys.java ExcFinallyDemo.java ExcCreatingExceptions.java ExcChainedExceptionDemo.java ExcOutOfRangeException.java) (goes with ExcCreatingExceptions)‏ ExcThrowDemo.java JamilGUICalculator.java ExcRethrow.java ExcProductCodes.java ExcNotHandled.java ExcCalculatorGUI.java
  • End of Presentation