Java Exception - PowerPoint PPT Presentation

1 / 29
About This Presentation
Title:

Java Exception

Description:

public class A extends. Exception { exception propagation. Jan. 2004. 4. Exceptions ... Exceptions of either class Error or RuntimeException do ... – PowerPoint PPT presentation

Number of Views:213
Avg rating:3.0/5.0
Slides: 30
Provided by: che88
Category:
Tags: exception | java

less

Transcript and Presenter's Notes

Title: Java Exception


1
Java Exception Yangjun Chen Dept. Business
Computing University of Winnipeg
2
Outline Exceptions
  • Exceptions
  • Managing Exceptions
  • try and catch blocks
  • finally clause
  • Exception propagation
  • Throwing Exceptions
  • Creating your own Exceptions

3
Outline Exceptions
Catching exception
Creating exception
Reporting exception
public boolean myM(int x) throws AnException
throw new AnException()
public class A extends Exception
try
catch
finally
exception propagation
4
Exceptions
  • Exceptions are unusual things that happen within
    your Java
  • program that are different from the desired
    behavior of the
  • program.
  • They could be fatal errors or could be in the
    event of
  • exceptional circumstances.
  • Exception handling is the management of these
    exceptions or errors.
  • When an exception is encountered, Java will
    report this
  • problem by throwing an exception.

5
Exceptions
  • At this point, the system will halt normal
    operation and look for a solution to the problem.
    It looks in your code, to see if there is
    anything that will catch the exception.
  • After the exception is caught, normal operation
    is resumed
  • after the offending block of code.
  • In traditional error handling, some code is
    usually written
  • to head off the error before it occurs.
  • Exception handling in Java allows the error or
    unusual
  • situation to occur and then takes steps to deal
    with it.
  • Exceptions dont occur in Java. They are thrown.
  • Exceptions can be thrown by either the system or
    by the
  • programmer.

6
Exceptions
  • Exceptions in Java are actual objects of classes
    that inherit
  • from the Throwable class.

ArithmeticException
RuntimeException
ArrayStoreException ...
ClassNotFoundException
NoSuchFieldException
NoSuchMethodException ...
Throwable
OutOfMemoryError
StackOverflowError ...
VirtualMachineError
LinkageError
ClassFormatError
ThreadDeath
NoClassDefFoundError ...
7
Throwable Class
  • The Throwable class has two subclasses Error and
  • Exception .
  • Instances of the Error class represent internal
    errors that are
  • usually fatal. You can neither catch them nor
    throw them
  • yourself.
  • The Exception subclass will contain most of the
    exception
  • classes that are used, but there are other
    packages that
  • define their own exception classes.
  • - For example, the java. io package has its own
    exception class
  • called IOException .
  • So how do we handle exceptions?

8
Managing Exceptions
  • The Java compiler will enforce exception
    management
  • when you try to use methods that declare
    exceptions. Your
  • program will not compile unless there is code
    that will
  • handle the exception.
  • Handling or catching an exception requires two
    things
  • - protecting the code that contains the method
    that throws an
  • exception by putting it inside a try block
  • - Testing and dealing with the exception in a
    catch block
  • What these two keywords mean is to try this code
    that
  • might cause an exception. If all works well,
    then continue
  • on. If it doesnt, then catch the problem and
    deal with it.
  • For example, lets look at the following code.

9
Try and Catch
  • All try blocks must have a catch block associated
    with it.
  • You can also have more than one catch clause
    associated
  • with each try block.
  • try
  • offset x / n
  • // anything from here down will be ignored if
    n is 0.
  • catch (ArithmeticException e)
  • offset 10
  • // Execution will continue from here after the
    exception is
  • // handled

10
Multiple Catch Clauses
  • catch clauses are examined from top to bottom,
    stopping at
  • the first clause that has an argument that is
    compatible with
  • the thrown exception and then skipping the
    remaining
  • clauses.
  • try
  • catch (Exception e) // Compatible with every
    exception
  • catch (ArithmeticException e) // will never
    be called

11
finally Clause
  • Suppose that there is some code that must be
    executed
  • whether an exception was thrown or not.
  • This is done in what is called the finally
    clause.
  • SomeFileClass f new SomeFileClass()
  • if (f. open(/ a/ file/ name/ path))
  • try
  • someReallyExceptionalMethod()
  • catch (IOException e)
  • // deal with them!!
  • finally
  • f. close()
  • //finally
  • //if

12
finally Clause
  • Instead of using the finally clause, you could
    put the code
  • in all the catch clauses as well as just outside
    them, but this
  • would be duplicating code.
  • A try block can have at most one finally clause
    and it must
  • appear immediately after the last catch clause.
  • If a try block has a finally clause, it does not
    have to have
  • any catch clauses.
  • As with catch, a finally clause must be
    associated with a try
  • block.

13
Exception Propagation
  • Exceptions are propagated if there isnt a catch
    clause
  • associated with the try block that has a
    compatible
  • exception type.
  • The system will then look for an enclosing try..
    catch pair
  • that has an appropriate catch clause.
  • try
  • try // exception thrown here
  • catch (SomeException e) // exception not
    caught here
  • catch (SomeOtherException e) // look here

14
Exception Propagation
  • If an appropriate catch clause is not found, the
    search
  • continues until it reaches the block which
    encloses the
  • entire method body.
  • If there is still no compatible catch clause, the
    search is
  • widened to include the block containing the
    method call.
  • This search continues on outward, until
    eventually the
  • exception is handled. If there doesnt exist any
    handling
  • for the exception, the Java environment will
    handle it for
  • you. Java will terminate you program!
  • This isnt always a bad idea. There are
    situations that
  • terminating the program will be better or is the
    only
  • alternative.

15
The throws Clause
  • To indicate that some code in the body of your
    method may
  • throw an exception, use the throws keyword after
    the
  • signature of the method.
  • - public boolean myMethod( int x) throws
    AnException
  • For multiple exception types, put them all in the
    throws
  • clause separated by commas.
  • You can also throw a superclass of a group of
    exceptions to
  • indicate that your method may throw any subclass
    of that
  • exception.
  • - public void myMethod2( int x) throws
    IOException
  • Exceptions of either class Error or
    RuntimeException do
  • not have to be included in the throws clause.
    Java gives
  • them special treatment. They are implicit
    exceptions.

16
The throws Clause
  • Declaring that your method throws an exception
    doesnt
  • actually make your method throw the exception if
    occurred.
  • This has to be done within the body of the
    method itself.
  • To throw an exception, an instance of some
    exception class
  • is needed. Once an instance is created or
    obtained, use the
  • throw statement to throw it.

17
The throws Clause
  • The simplest way is to create the instance and
    throw the
  • exception in the same statement.
  • - throw new ServiceNotAvailableException()
  • You can only throw objects that are instances of
    subclasses
  • of Throwable unlike in C where an object of
    any type
  • may be thrown.
  • Depending on the exception class that you are
    using, the
  • exceptions constructor may require some
    arguments. The
  • most common argument is a string that describes
    the
  • exception in more detail.
  • - throw new ServiceNotAvailableException(
    Exception
  • service not available, database is offline.)

18
The throws Clause
  • Once an exception is thrown, the method exits
    after
  • executing the finally clause (if one exists)
    without returning
  • a value.
  • The exception is then passed on to the
    surrounding
  • try.. catch block and propagated further until
    it is handled.

19
Creating Exceptions
  • Although Java provides a wealth of exception
    classes, there
  • may be times where we would like to create our
    own
  • exceptions that are not covered by the
    predefined exception
  • classes.
  • To create a exception, you must inherit from one
    of the
  • other exception classes. Try to find an
    exception thats
  • close to the one you are creating.
  • If none of the exceptions match closely, then
    inherit from
  • Exception itself which is the top of the
    hierarchy for
  • explicit exceptions or RuntimeException.
  • Exception classes typically have two
    constructors, one with
  • no arguments and one with a string argument.

20
Creating Exceptions
  • The MissingData exception is thrown in a utility
    method.
  • class MissingData extends Exception
  • // thrown by the processSubmitButton() when one
    or more of the
  • // data fields are empty
  • public MissingData()
  • super()
  • public MissingData( String s)
  • super(s)

21
Creating Exceptions
private void processSubmitButton() throws
MissingData if (( custName. getText().
equals( EMPTY)) (custStreet. getText().
equals( EMPTY) //( six more clauses
omitted here) (order. getText(). equals(
EMPTY))) throw new MissingData( Complete
all fields!) else // Data is all
there order. appendText( CRLF ORDER
PLACED) repaint() //else //
processSubmitButton
22
Creating Exceptions
  • Note that we have to use a throws clause, since
    MissingData is a checked exception.
  • Now the exception is caught in the applets
    action() handler.
  • else if (e. target Submit)
  • try
  • processSubmitButton()
  • catch (MissingData ex)
  • order.appendText( ex.getMessage() CRLF)
  • repaint()
  • return true

23
An Example for Exception Propagation
import java.lang. //Here we define some
exception types of our own. //Exception classes
generally have constructors but no data
or //other methods. All these do is call their
superclass constructors. class MyException
extends Exception public MyException()
super() public MyException(String s)
super(s) class MyOtherException extends
Exception public MyOtherException
super() public MyOtherException(String s)
super(s)
24
An Example for Exception Propagation
class MySubException extends MyException
public MySubException() super() public
MySubException(String s) super(s) public
class Throwtest //This is the main() method.
Note that it uses two //catch clauses to handle
two standard Java exceptions. public static
void main(String argv) int i 2
25
An Example for Exception Propagation
//First, covert our argument to an integer.
//Make sure we have an argument and that it is
convertible. try i Integer.parseInt(argv0
catch (ArrayIndexOutOfBoundsException e)
//argv is empty System.out.println("Must
specify an argument") return catch
(NumberFormatException e) //argv0 is not an
integer System.out.println("Must specify an
integer argument")
26
An Example for Exception Propagation
//Now, oass that integer to method a().
a(i) //This method invokes b(), which is
declared to throw //one type of exception. We
handle that one exception. public static void
a(int i) try b(i)
27
An Example for Exception Propagation
catch (MyException e) //Point 1 //Here we
handle MyException and its subclass
MySubException if (e instanceof MySubException)
System.out.print("MySubException ") else
System.out.print("MyException ") System.out.pri
ntln(e.getMessage()) System.out.println("Handle
at point 1")
28
An Example for Exception Propagation
public static void b(int i) throws MyException
int result try System.out.print("i
" i) result c(i) System.out.print("
c(i) " result) catch
(MyOtherException e) //Point 2 //Handle
MyOtherException System.out.println("MyOtherExce
ption " e.getMessage()) System.out.println("H
andle at point 2")
29
An Example for Exception Propagation
finally //Terminate the output we printed
above with a newline. System.out.print("\n")

public static int c(int i) throws MyException,
MyOtherException switch (i) case 0
//processing resumes at point 1 above throw
new MyException("input too low") case 1
//processing resumes at point 1 above throw
new MyException("input still too low") case 99
//processing resumes at point 2 above throw
new MyOtherException("input too
high") default return ii
Write a Comment
User Comments (0)
About PowerShow.com