chapter 12 handling exceptions and events l.
Download
Skip this Video
Loading SlideShow in 5 Seconds..
Chapter 12: Handling Exceptions and Events PowerPoint Presentation
Download Presentation
Chapter 12: Handling Exceptions and Events

Loading in 2 Seconds...

play fullscreen
1 / 51

Chapter 12: Handling Exceptions and Events - PowerPoint PPT Presentation


  • 151 Views
  • Uploaded on

Chapter 12: Handling Exceptions and Events. J ava P rogramming: From Problem Analysis to Program Design, Second Edition. Objectives. Learn what an exception is. See how a try / catch block is used to handle exceptions. Become aware of the hierarchy of exception classes.

loader
I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
capcha
Download Presentation

PowerPoint Slideshow about 'Chapter 12: Handling Exceptions and Events' - said


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.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
chapter 12 handling exceptions and events

Chapter 12: Handling Exceptions and Events

JavaProgramming:

From Problem Analysis to Program Design,

Second Edition

objectives
Objectives
  • Learn what an exception is.
  • See how a try/catch block is used to handle exceptions.
  • Become aware of the hierarchy of exception classes.
  • Learn about checked and unchecked exceptions.
  • Learn how to handle exceptions within a program.
  • Discover how to throw and rethrow an exception.
  • Learn how to handle events in a program.

Java Programming: From Problem Analysis to Program Design, Second Edition

exception
Exception
  • An occurrence of an undesirable situation that can be detected during program execution.
  • Examples:
    • Division by zero.
    • Trying to open an input file that does not exist.
    • An array index that goes out of bounds.

Java Programming: From Problem Analysis to Program Design, Second Edition

handling exceptions within a program
Handling Exceptions within a Program
  • Can use an if statement to handle an exception.
  • However, suppose that division by zero occurs in more than one place within the same block.
    • In this case, using ifstatements may not be the most effective way to handle the exception.

Java Programming: From Problem Analysis to Program Design, Second Edition

java s mechanism of exception handling
Java’s Mechanism of Exception Handling
  • When an exception occurs, an object of a particular exception classis created.
  • Java provides a number of exception classes to effectively handle certain common exceptions, such as:
    • Division by zero
    • Invalid input
    • File not found

Java Programming: From Problem Analysis to Program Design, Second Edition

java s mechanism of exception handling6
Java’s Mechanism of Exception Handling
  • Division by zero is:
    • An arithmetic error.
    • Handled by the classArithmeticException.
  • When a division by zero exception occurs, the program creates an object of the classArithmeticException.

Java Programming: From Problem Analysis to Program Design, Second Edition

java s mechanism of exception handling7
Java’s Mechanism of Exception Handling
  • When a Scanner object is used to input data into a program, any invalid input errors are handled using the classInputMismatchException.
  • The classException (directly or indirectly) is the superclass of all the exception classes in Java.

Java Programming: From Problem Analysis to Program Design, Second Edition

try catch finally block
try/catch/finally Block
  • Statements that might generate an exception are placed in a tryblock.
  • The tryblock:
    • Might also contain statements that should not be executed if an exception occurs.
    • Is followed by zero or more catchblocks.
  • A catchblock:
    • Specifies the type of exception it can catch.
    • Contains an exception handler.

Java Programming: From Problem Analysis to Program Design, Second Edition

try catch finally block9
try/catch/finallyBlock
  • The last catchblock may or may not be followed by a finallyblock.
  • Any code contained in a finallyblock always executes regardless of whether an exception occurs, except when the program exits early from a tryblock by calling the method System.exit.
  • If a tryblock has no catchblock, then it must have the finallyblock.

Java Programming: From Problem Analysis to Program Design, Second Edition

try catch finally block10
try/catch/finallyBlock

Java Programming: From Problem Analysis to Program Design, Second Edition

try catch finally block11
try/catch/finallyBlock
  • If no exception is thrown in a tryblock, all catchblocks associated with the tryblock are ignored and program execution resumes after the last catchblock.
  • If an exception is thrown in a tryblock, the remaining statements in the tryblock are ignored.
  • The program searches the catchblocks in the order in which they appear after the tryblock and looks for an appropriate exception handler.

Java Programming: From Problem Analysis to Program Design, Second Edition

try catch finally block12
try/catch/finallyBlock
  • If the type of the thrown exception matches the parameter type in one of the catchblocks, the code of that catchblock executes and the remaining catchblocks are ignored.
  • If there is a finallyblock after the last catchblock, the finallyblock executes regardless of whether an exception occurs.

Java Programming: From Problem Analysis to Program Design, Second Edition

order of catch blocks
Order of catch Blocks
  • The heading of a catchblock specifies the type of exception it handles.
  • A catchblock can catch either all exceptions of a specific type or all types of exceptions.
  • A reference variable of a superclass type can point to an object of its subclass.

Java Programming: From Problem Analysis to Program Design, Second Edition

order of catch blocks14
Order of catch Blocks
  • If you declare an exception using the classException in the heading of a catchblock, then that catchblock can catch all types of exceptions because the classException is the superclass of all exception classes.
  • In a sequence of catchblocks following a tryblock, a catchblock that declares an exception of a subclass type should be placed before catchblocks that declare exceptions of a superclass type.

Java Programming: From Problem Analysis to Program Design, Second Edition

order of catch blocks15
Order of catch Blocks

Java Programming: From Problem Analysis to Program Design, Second Edition

slide16

Order of catch Blocks

Java Programming: From Problem Analysis to Program Design, Second Edition

slide17

Order of catch Blocks

Java Programming: From Problem Analysis to Program Design, Second Edition

slide18

Order of catch Blocks

Java Programming: From Problem Analysis to Program Design, Second Edition

slide19

Order of catch Blocks

Java Programming: From Problem Analysis to Program Design, Second Edition

java s exception class
Java’s Exception Class
  • classException:
    • Subclass of classThrowable.
    • Superclass of classes designed to handle exceptions.
  • Various types of exceptions:
    • I/O exceptions.
    • Number format exceptions.
    • File not found exceptions.
    • Array index out of bounds exceptions.
  • Various exceptions categorized into separate classes and contained in various packages.

Java Programming: From Problem Analysis to Program Design, Second Edition

java s exception class21
Java’s Exception Class

Java Programming: From Problem Analysis to Program Design, Second Edition

java s exception class22
Java’s Exception Class

Java Programming: From Problem Analysis to Program Design, Second Edition

java s exception class23
Java’s Exception Class

Java Programming: From Problem Analysis to Program Design, Second Edition

java s exception class24
Java’s Exception Class

Java Programming: From Problem Analysis to Program Design, Second Edition

java s exception class25
Java’s Exception Class

Java Programming: From Problem Analysis to Program Design, Second Edition

java s exception class26
Java’s Exception Class

Java Programming: From Problem Analysis to Program Design, Second Edition

checked exceptions
Checked Exceptions
  • Any exception that can be analyzed by the compiler.
  • Example:
    • FileNotFoundExceptions.

Java Programming: From Problem Analysis to Program Design, Second Edition

unchecked exceptions
Unchecked Exceptions
  • Exceptions that cannot be analyzed when the program compiles (must be checked for by programmer).
  • Examples:
    • Division by zero
    • Array index out of bounds
  • Syntax:

throws ExceptionType1, ExceptionType2,...

ExceptionType1, ExceptionType2, and so on are names of exception classes

Java Programming: From Problem Analysis to Program Design, Second Edition

exceptions example code
Exceptions Example Code

public static void exceptionMethod()

throws InputMismatchException,

FileNotFoundException

{

//statements

}

  • The method exceptionMethod throws exceptions of the type InputMismatchException and FileNotFoundException.

Java Programming: From Problem Analysis to Program Design, Second Edition

the class exception and the operator instanceof
The classException and the Operator instanceof
  • A reference of a superclass type can point to objects of its subclass.
  • You can determine if a reference variable points to an object using the operator instanceof.
  • You can combine catch blocks using this facility.

Java Programming: From Problem Analysis to Program Design, Second Edition

slide31

The classException and the Operator instanceof

try

{

System.out.print("Line 4: Enter the "

+ "dividend: ");

dividend = console.nextInt();

System.out.println();

System.out.print("Line 7: Enter the "

+ "divisor: ");

divisor = console.nextInt();

System.out.println();

quotient = dividend / divisor;

System.out.println("Line 11: Quotient = "

+ quotient);

}

catch (Exception eRef)

{

if (eRef instanceof ArithmeticException)

System.out.println("Line 14: Exception "

+ eRef.toString());

else if (eRef instanceof InputMismatchException)

System.out.println("Line 16: Exception "

+ eRef.toString());

}

Java Programming: From Problem Analysis to Program Design, Second Edition

rethrowing and throwing an exception
Rethrowing and Throwing an Exception
  • When an exception occurs in a tryblock, control immediately passes to one of the catchblocks.
  • Typically, a catchblock does one of the following:
    • Completely handles the exception.
    • Partially processes the exception.
      • In this case, the catchblock either rethrows the same exception or throws another exception for the calling environment to handle the exception.
    • Rethrows the same exception for the calling environment to handle the exception.

Java Programming: From Problem Analysis to Program Design, Second Edition

rethrowing and throwing an exception33
Rethrowing and Throwing an Exception
  • Useful when:
    • Catch block catches exception but is unable to handle it.
    • Catch block decides exception should be handled by calling environment.
  • Allows programmer to provide exception handling code in one place.
  • Syntax:

throw exceptionReference;

Java Programming: From Problem Analysis to Program Design, Second Edition

rethrowing and throwing an exception34
Rethrowing and Throwing an Exception

import java.util.*;

public class RethrowExceptionExmp1

{

static Scanner console = new Scanner(System.in);

public static void main(String[] args)

{

int number;

try

{

number = getNumber();

System.out.println("Line 5: number = "

+ number);

}

catch (InputMismatchException imeRef)

{

System.out.println("Line 7: Exception "

+ imeRef.toString());

}

}

}

Java Programming: From Problem Analysis to Program Design, Second Edition

rethrowing and throwing an exception35
Rethrowing and Throwing an Exception

public static int getNumber()

throws InputMismatchException

{

int num;

try

{

System.out.print("Line 11: Enter an “

+ "integer: ");

num = console.nextInt();

System.out.println();

return num;

}

catch (InputMismatchException imeRef)

{

throw imeRef;

}

}

}

Java Programming: From Problem Analysis to Program Design, Second Edition

the method printstacktrace
The Method printStackTrace
  • Used to determine the order in which the methods were called and where the exception was handled.

Java Programming: From Problem Analysis to Program Design, Second Edition

the method printstacktrace37
The Method printStackTrace

import java.io.*;

public class PrintStackTraceExample1

{

public static void main(String[] args)

{

try

{

methodA();

}

catch (Exception e)

{

System.out.println(e.toString()

+ " caught in main");

e.printStackTrace();

}

}

Java Programming: From Problem Analysis to Program Design, Second Edition

the method printstacktrace38
The Method printStackTrace

public static void methodA() throws Exception

{

methodB();

}

public static void methodB() throws Exception

{

methodC();

}

public static void methodC() throws Exception

{

thrownew Exception("Exception generated "

+ "in method C");

}

}

Java Programming: From Problem Analysis to Program Design, Second Edition

the method printstacktrace39
The Method printStackTrace

Sample Run:

java.lang.Exception: Exception generated in method C caught in main

java.lang.Exception: Exception generated in method C

at PrintStackTraceExample1.methodC

(PrintStackTraceExample1.java:31)

at PrintStackTraceExample1.methodB

(PrintStackTraceExample1.java:26)

at PrintStackTraceExample1.methodA

(PrintStackTraceExample1.java:22)

at PrintStackTraceExample1.main

(PrintStackTraceExample1.java:11)

Java Programming: From Problem Analysis to Program Design, Second Edition

exception handling techniques
Exception-Handling Techniques
  • Terminate program.
    • Output appropriate error message upon termination.
  • Fix error and continue.
    • Repeatedly get user input.
    • Output appropriate error message until valid value is entered.
  • Log error and continue.
    • Write error messages to file and continue with program execution.

Java Programming: From Problem Analysis to Program Design, Second Edition

creating your own exception classes
Creating Your Own Exception Classes
  • Exception class you define extends classException or one of its subclasses.
  • Syntax to throw your own exception object:

throw new ExceptionClassName(messageString);

Java Programming: From Problem Analysis to Program Design, Second Edition

creating your own exception classes42
Creating Your Own Exception Classes

public class MyDivisionByZeroException

extends Exception

{

public MyDivisionByZeroException()

{

super("Cannot divide by zero");

}

public MyDivisionByZeroException(String

strMessage)

{

super(strMessage);

}

}

Java Programming: From Problem Analysis to Program Design, Second Edition

event handling
Event Handling
  • Action events:
    • Handled by implementing interface ActionListener.
  • Window events:
    • Handled by implementing interface WindowListener.
  • Mouse events:
    • Handled by implementing interface MouseListener.
  • Key events:
    • Handled by implementing interface KeyListener.

Java Programming: From Problem Analysis to Program Design, Second Edition

event handling44
Event Handling
  • class WindowAdapter:
    • Implements interfaceWindowListener with empty bodies to methods.
  • classMouseAdapter:
    • Implements interface MouseListener with empty bodies to methods.

Java Programming: From Problem Analysis to Program Design, Second Edition

registering listeners
Registering Listeners
  • To register window listener object to GUI component:
    • Use method addWindowListener.
    • Window listener object being registered is passed as parameter to method addWindowListener.
  • To register mouse listener object to GUI component:
    • Use method addMouseListener.
    • Mouse listener object being registered is passed as parameter to method addMouseListener.

Java Programming: From Problem Analysis to Program Design, Second Edition

registering listeners46
Registering Listeners

Java Programming: From Problem Analysis to Program Design, Second Edition

registering listeners47
Registering Listeners

Java Programming: From Problem Analysis to Program Design, Second Edition

registering listeners48
Registering Listeners

Java Programming: From Problem Analysis to Program Design, Second Edition

programming example calculator
Programming Example: Calculator

Java Programming: From Problem Analysis to Program Design, Second Edition

chapter summary
Chapter Summary
  • Exception definition
  • Handling exceptions within a program:
    • try/catch/finally block.
    • Order of catch blocks.
    • Using try/catch blocks in a program.
    • The classException and the Operator instanceof.
    • Rethrowing and throwing an exception.

Java Programming: From Problem Analysis to Program Design, Second Edition

chapter summary51
Chapter Summary
  • Exception
    • Hierarchy
    • Classes
  • Checked and unchecked exceptions
  • The method printStackTrace
  • Exception handling techniques:
    • Terminate program.
    • Fix error and continue.
    • Log error and continue.
  • Creating your own exception classes
  • Event handling

Java Programming: From Problem Analysis to Program Design, Second Edition