Exceptions - PowerPoint PPT Presentation

1 / 47
About This Presentation
Title:

Exceptions

Description:

Exceptions and Errors are objects representing ... is either checked or unchecked ... An unchecked exception does not require explicit handling, though ... – PowerPoint PPT presentation

Number of Views:168
Avg rating:3.0/5.0
Slides: 48
Provided by: john1387
Category:

less

Transcript and Presenter's Notes

Title: Exceptions


1
  • Exceptions

2
Exceptions
  • Exceptions and Errors are objects representing
    incorrect behavior.
  • An exception is thrown by the program or run time
    environment and can be caught by the program.
  • An Error is a very bad misbehaviour and should
    not be caught.
  • Exception and Error are predefined classes,with
    some predefined subclasses.
  • User can define new Exception classes extending
    the predefined ones.

Class Throwable
Class Error
Class Exception
3
Introduction
  • Errors can be dealt with at place error occurs
  • Easy to see if proper error checking implemented
  • Harder to read application itself and see how
    code works
  • Exception handling
  • Makes clear, robust, fault-tolerant programs
  • Java removes error handling code from "main line"
    of program
  • Example of common failures
  • Memory exhaustion
  • Out of bounds array subscript
  • Division by zero
  • Invalid method parameters

4
When Should Exception Handling Be Used
  • Error handling used for
  • Processing exceptional situations
  • Processing exceptions for components that cannot
    handle them directly
  • Processing exceptions for widely used components
    (libraries, classes, methods) that should not
    process their own exceptions
  • Large projects that require uniform error
    processing

5
Other Error Handling Techniques
  • Other techniques
  • Ignore exceptions
  • Personal programs usually ignore errors
  • Not for commercial software
  • Abort
  • Fine for most programs
  • Inappropriate for mission critical programs

6
The Basics of Java Exception Handling
  • Exception handling
  • Method detects error it cannot deal with
  • Throws an exception
  • Exception handler
  • Code to catch exception and handle it
  • Exception only caught if handler exists
  • If exception is not caught, the block terminates

7
The Basics of Java Exception Handling
  • Enclose code that may have an error in try block
  • Follow with one or more catch blocks
  • Each catch block is an exception handler
  • If exception occurs and matches the parameter of
    a catch block
  • Code in catch block is executed
  • If no exception thrown
  • Exception handling code is skipped
  • Control resumes after the catch blocks

try code that may throw exceptions catch
(ExceptionType ref) exception handling code
8
The Basics of Java Exception Handling
  • Termination model of exception handling
  • throw point
  • Place where exception occurred
  • Control cannot return to throw point
  • Block which threw exception expires
  • Possible to give information to exception handler

9
Exceptions
  • An Exception is an object that describes an
    unusual or erroneous situation
  • Exceptions are thrown by a program, and may be
    caught and handled by another part of the program
  • A program can therefore be separated into a
    normal execution flow and an exception execution
    flow
  • An error is also represented as an object in
    Java, but usually represents a unrecoverable
    situation and should not be caught

10
Exception Handling
  • A program can deal with an exception in one of
    three ways
  • ignore it
  • handle it where it occurs
  • handle it in another part of the program
  • The manner in which an exception is processed is
    an important design consideration

11
Exception Handling
  • If an exception is ignored by the program, the
    program will terminate and produce an appropriate
    message
  • The message includes a call stack trace that
    indicates on which line the exception occurred,
  • The call stack trace also shows the method call
    trail that lead to the execution of the offending
    line

12
// Demonstrates an uncaught exception. //

public class Zero
//------------------------------------------------
----------------- // Deliberately divides by
zero to produce an exception.
//------------------------------------------------
----------------- public static void main
(String args) int numerator 10
int denominator 0 System.out.println
(numerator / denominator) exception
System.out.println ("This text will not be
printed.") never executed
Exception in thread main java.lang.ArithmeticEx
ception / by zero at Zero.main(Zero.java17)
Calss.method(fileline )
13
Catching Exceptions The try Statement
  • To process an exception when it occurs, the line
    that throws the exception is executed within a
    try block
  • A try block is followed by one or more catch
    clauses, which contain code to process an
    exception
  • Each catch clause has an associated exception
    type
  • When an exception occurs, processing continues at
    the first catch clause that matches the exception
    type

14
// Demonstrates the use of a try-catch
block. //
import
cs1.Keyboard public class ProductCodes
//------------------------------------------------
----------------- // Counts the number of
product codes that are entered with a // zone
of R and district greater than 2000.
//------------------------------------------------
----------------- public static void main
(String args) String code
char zone int district, valid 0, banned
0 System.out.print ("Enter product code
(XXX to quit) ") code
Keyboard.readString()
15
while (!code.equals ("XXX")) try
zone code.charAt(9)
district Integer.parseInt(code.substring(3,
7)) valid if (zone
'R' district gt 2000) banned
catch (StringIndexOutOfBoundsEx
ception exception)
System.out.println ("Improper code length "
code) catch
(NumberFormatException exception)
System.out.println ("District is not
numeric " code)
System.out.print ("Enter product code (XXX to
quit) ") code Keyboard.readString()
System.out.println (" of valid codes
entered " valid) System.out.println (" of
banned codes entered " banned)
16
The finally Clause
  • A try statement can have an optional clause
    designated by the reserved word finally
  • If no exception is generated, the statements in
    the finally clause are executed after the
    statements in the try block complete
  • Also, if an exception is generated, the
    statements in the finally clause are executed
    after the statements in the appropriate catch
    clause complete

17
Exception Propagation
  • If it is not appropriate to handle the exception
    where it occurs, it can be handled at a higher
    level
  • Exceptions propagate up through the method
    calling hierarchy until they are caught and
    handled or until they reach the outermost level
  • A try block that contains a call to a method in
    which an exception is thrown can be used to catch
    that exception

18
// Demonstrates exception propagation. //

public class ExceptionScope
//------------------------------------------------
----------------- // Catches and handles the
exception that is thrown in level3.
//------------------------------------------------
----------------- public void level1()
System.out.println("Level 1 beginning.")
try level2( ) catch
(ArithmeticException problem)
System.out.println ()
System.out.println ("The exception message is "
problem.getMessage())
System.out.println ()
System.out.println ("The call stack trace")
problem.printStackTrace()
System.out.println ()
19
System.out.println("Level 1 ending.")
//------------------------------------------------
----------------- // Serves as an
intermediate level. The exception propagates
// through this method back to level1.
//------------------------------------------------
----------------- public void level2()
System.out.println("Level 2 beginning.")
level3 ( ) System.out.println("Level 2
ending.") //-----------------------------
------------------------------------ //
Performs a calculation to produce an exception.
It is not // caught and handled at this
level. //--------------------------------------
--------------------------- public void level3
( ) int numerator 10, denominator
0 System.out.println("Level 3
beginning.") int result numerator /
denominator System.out.println("Level 3
ending.")
20
// Demonstrates exception propagation. //
public
class Propagation //-------------------------
---------------------------------------- //
Invokes the level1 method to begin the exception
demonstation. //-------------------------------
---------------------------------- static
public void main (String args)
ExceptionScope demo new ExceptionScope()
System.out.println("Program beginning.")
demo.level1() System.out.println("Program
ending.")
Program beginning level 1 beginning level 2
beginning level 3 beginning The exception message
is . level 1 ending Program ending
21
Trowing Exceptions The throw Statement
  • A programmer can define an exception by extending
    the appropriate Exception subclassclass
  • Exceptions are thrown using the throw statement
  • Usually a throw statement is nested inside an if
    statement that evaluates the condition to see if
    the exception should be thrown

22
Exception Handling summary
  • A Try Block - Enclose in a try block the code
    where exception can occur code that should not
    be executed if exception occurs
  • Throw an exception In a method definition,need
    to specify the type of exception the method
    throws. After parameters, before code.
  • Catch an exception - a list of catch blocks
    following the try block
  • specify the type of exception and the
    exception handling.
  • Rethrow an exception
  • A Finally Clause Follows the last catch block

23
Scheme
  • public void mymethode(a,b,c) throws
    DivideByZeroException,
  • try throw .
  • cath(DevideByZero) ..
  • catch(..)
  • finally.
  • .

1. By this method or other methods
called by this method 2. Can throw these types
Or their subtypes 3. Should list all but
runtime exceptions
Zero or more
24
Catch
  • If no matching catch block go to the next
    enclosing try block
  • A cath block contains an exception handler
  • Catch(Exception exception)
  • Catch block list
  • Catch (Exception x) must be the last in the
    list or all others will be ignored. It catches
    ALL exceptions.

25
// Demonstrates the ability to define an
exception via inheritance. //
import
OutOfRangeException import cs1.Keyboard public
class CreatingExceptions //--------------------
---------------------------------------------
// Creates an exception object and possibly
throws it. //----------------------------------
------------------------------- public static
void main (String args) throws
OutOfRangeException final int MIN
25, MAX 40 OutOfRangeException problem
new OutOfRangeException ("Input value
is out of range.") System.out.print
("Enter an integer value between " MIN
" and " MAX ", inclusive
") int value Keyboard.readInt()
// Determines if the exception should be thrown
if (value lt MIN value gt MAX)
throw problem System.out.println ("End of
main method.") // may never reach
26
Checked Exceptions
  • An exception is either checked or unchecked
  • A checked exception can only be thrown within a
    try block or within a method that is designated
    to throw that exception
  • The compiler will complain if a checked exception
    is not handled appropriately
  • An unchecked exception does not require explicit
    handling, though it could be processed that way

27
An Exception Handling Example Divide by Zero
  • Example program
  • User enters two integers to be divided
  • We want to catch division by zero errors
  • Exceptions
  • Objects derived from class Exception
  • Look in Exception classes in java.lang
  • Nothing appropriate for divide by zero of
    floating poin (ArithmeticException for
    divide-by-zero with integers)
  • Closest is ArithmeticException
  • Extend and create our own exception class

28
(No Transcript)
29
  • 1. Set up GUI

30
  • 2. Process GUI events
  • 2.1 try block

No throw clause Since caught within This
method. Catch-or-declare strategy
31
  • 2.2 catch blocks
  • 3. quotient
  • 4. main

Throw clause, Because NOT Caught in this method
32
(No Transcript)
33
Try Blocks
  • Exceptions that occurs in a try block
  • Usually caught by handler specified by following
    catch block
  • Can have any number of catch blocks
  • If no exceptions thrown, catch blocks skipped

try code that may throw exceptions catch (
ExceptionType ref ) exception handling code
34
Throwing an Exception
  • throw
  • Indicates exception has occurred (throwing an
    exception)
  • Operand
  • Object of any class derived from Throwable
  • Derived from Throwable
  • Exception - most programmers deal with
  • Error - serious, should not be caught
  • When exception thrown
  • Control exits current try block
  • Proceeds to catch handler (if exists)

35
Throwing an Exception
  • RunTime Exceptions
  • Can still throw exceptions without explicit throw
    statement
  • ArrayIndexOutOfBoundsException
  • Terminates block that threw exception
  • Not required to terminate program

36
Catching an Exception
  • Catching exceptions
  • First handler to match exception, catch it
  • All other handlers skipped
  • If exception not caught
  • Searches enclosing try blocks for appropriate
    handler
  • If still not caught, non-GUI based applications
    terminate

try try throw Exception2 catch
( Exception1 )...catch( Exception2 )...
37
Rethrowing an Exception
  • An exception handler can rethrowing the exception
  • Used if handler cannot process exception
  • Rethrow exception with the statement
  • throw e
  • Detected by next enclosing try block
  • Handler can always rethrow exception, even if it
    has performed some processing, (thus can both
    process exception and let more processing be
    performed by handler of enclosing try.

38
Throws Clause
  • Throws clause
  • Lists exceptions that can be thrown by a method
  • Method can throw listed exceptions or derived
    types

int g( float h ) throws a, b, c // method
body
39
Throws Clause
  • Run-time exceptions
  • Derive from RunTimeException
  • Some exceptions can occur at any point
  • ArrayIndexOutOfBoundsException
  • NullPointerException
  • Create object reference without attaching object
    to reference
  • ClassCastException
  • Invalid casts
  • Most avoidable by writing proper code

40
Throws Clause
  • Checked exceptions
  • Must be listed in throws clause of method
  • All non-RuntimeExceptions
  • Unchecked exceptions
  • Can be thrown from almost any method
  • Tedious to write throws clause every time
  • No throws clause needed
  • Errors and RunTimeExceptions

41
Throws Clause
  • Catch-or-declare requirement
  • If method calls another method that explicitly
    throws checked exceptions
  • Exceptions must be in original method's throws
    clause
  • Otherwise, original method must catch exception
  • Method must either catch exception or declare it
    in the throw clause

42
Exceptions and Inheritance
  • Inheritance
  • Exception classes can have a common superclass
  • catch ( Superclass ref )
  • Catches subclasses
  • Polymorphic processing
  • Easier to catch superclass than catching every
    subclass

43
finally Block
  • finally block
  • Placed after last catch block
  • Can be used to returns resources allocated in the
    try block
  • Always executed, regardless whether exceptions
    thrown or caught
  • Cases
  • No exception in try block
  • Exception occurs caught by a carch
  • Exception occurs but not caught by a catch
    associated with current try block

44
  • 1. main
  • 1.1 throwException
  • 1.2 catch
  • 2. Define throwException
  • 2.1 try
  • 2.2 catch
  • 2.3 finally

Handle the exception
45
Using printStackTrace and getMessage
  • Class Throwable
  • Superclass of all exceptions
  • Method printStackTrace
  • Prints method call stack for caught Exception
    object
  • Most recent method on top of stack
  • Helpful for testing/debugging
  • Constructors of the class Throwable
  • Exception()
  • Exception( String informationString )
  • informationString may be accessed with method
    getMessage

46
  • 1. main
  • 1.1 try
  • 1.2 getMessage
  • 1.3 printStackTrace
  • 2. method1
  • 3. method2
  • 4. method3
  • 4.1 throw

47
Exception thrown in method3 java.lang.Exception
Exception thrown in method3 at
UsingExceptions.method3(UsingExceptions.java28)
at UsingExceptions.method2(UsingExceptions.
java23) at UsingExceptions.method1(UsingE
xceptions.java18) at UsingExceptions.main
(UsingExceptions.java8)
Write a Comment
User Comments (0)
About PowerShow.com