Exceptions - PowerPoint PPT Presentation

1 / 26
About This Presentation
Title:

Exceptions

Description:

radix (as determined by whether Character.digit(char, int) returns ... Any character of the string is not a digit of the specified radix, except that the first ... – PowerPoint PPT presentation

Number of Views:56
Avg rating:3.0/5.0
Slides: 27
Provided by: vm66
Category:
Tags: exceptions | radix

less

Transcript and Presenter's Notes

Title: Exceptions


1
Exceptions
2
Useful links for Exceptions
  • Tutorial on exceptionshttp//www.artima.com/desig
    ntechniques/exceptions.html
  • The Java Tutorial on Exceptionshttp//java.sun.co
    m/docs/books/tutorial/essential/exceptions/index.h
    tml
  • The Exceptions chapter of the Java Language
    Specification (a technical explanation)http//jav
    a.sun.com/docs/books/jls/html/11.doc.html
  • An explanation of try-catch-finally blocks from
    the Java Language Specification (a technical
    explanation) http//java.sun.com/docs/books/jls/h
    tml/14.doc.html79311

3
Handling errors
  • What happens if someone attempts to add an item
    to a queue that is full?
  • Many times it is the client that knows what the
    appropriate thing to do is in the case of an
    error.
  • Exceptions provide a method of informing a client
    that an error has occurred and provides a
    mechanism for handling the error cleanly.
  • Many languages provide support for exceptions.

4
Why Exceptions?
  • Exceptions are the right way to handle errors
    that occur in a program.
  • For instance, assume that a method with the
    signature
  • double squareRoot(double value)
  • is written. What would the value of root be
    in the statement
  • double root squareRoot(-1.0)
  • Exceptions make program errors easier to identify
    and eliminate by organizing a program into
    sections for the normal case and the
    exceptional case.

5
Java Exception Handling
  • An exception occurs, thrown, when something goes
    wrong while a program is running.
  • If an exception is not handled, caught, the
    program will terminate.
  • When an exception is thrown, the exception is
    passed to the caller of the method.
  • The caller can then handle the exception or allow
    it to propagate back up the call chain.

6
Exception terminology
  • Throwing an exception
  • Occurs when an Exception object is created and
    thrown.
  • Handling an exception
  • Occurs when a thrown Exception is caught. This
    is also called catching an exception.
  • Java Syntax
  • The normal case is handled in a try block
  • The exceptional case is handled in a catch block
  • The catch block takes a parameter of type
    Exception which specifies the kind of Exceptions
    that it catches.

7
Syntax
  • try
  • ltcode to try. Any Java code can be placed
    heregt
  • if(some_error_occurs)
  • throw new Exception(An error has
    occurred")
  • ltcode to try. Any Java code can be placed
    heregt
  • catch(Exception e)
  • lterror handling code. Any code will dogt
  • finally
  • ltpossibly more codegt
  • A try block is wrapped around code that may cause
    an exception.
  • A catch blocks following the try block can
    contain code to deal with the exception.
  • A finally block contains code that will be
    executed whether or not an exception occurs.
  • In most cases try and catch blocks suffice

8
How does it work?
  • Try block
  • Statements execute normally until a throw
    statement is executed.
  • If a throw statement is executed, control passes
    to the catch block(s) associated with the try
    block
  • Catch block
  • Executes only if an exception is thrown from the
    associated try block.
  • Normal execution resumes after the catch block

9
Example 1AChecking for valid data
  • int age
  • try
  • System.out.print(Enter your age )
  • age Keyboard.readInt()
  • if(age lt 0 age gt 120)
  • throw new Exception(Invalid age age)
  • System.out.println(Your age is age)
  • catch (Exception e)
  • System.out.println(e.getMessage())
  • System.out.println(Done.)

10
Example 1BChecking for valid data
  • int age
  • try
  • System.out.print(Enter your age )
  • age Keyboard.readInt()
  • if(age lt 0 age gt 120)
  • throw new Exception(Invalid age age)
  • System.out.println(Your age is age)
  • catch (Exception e)
  • System.out.println(e.getMessage())
  • System.out.println(Done.)

11
Example 2
  • int a new int2
  • try
  • for(int i0 ilt4 i)
  • ai 0
  • System.out.println(Done with the try block)
  • catch (ArrayIndexOutOfBoundsException e)
    System.out.println(e.getMessage())
  • System.out.println(Array a is initialized.)

12
Exception classes
  • Exceptions are objects!
  • Exception is the root class of all exceptions
  • Every exception has a getMessage( ) method that
    can be used for debugging or to produce useful
    messages to the user of your program
  • Many pre-defined methods throw exceptions
  • the documentation or source code will tell you
    when
  • the exceptions thrown are also pre-defined

13
Some Java Exceptions
  • ActivationException
  • ApplicationException
  • AWTException
  • ClassNotFoundException,
  • DataFormatException
  • GeneralSecurityException
  • IllegalAccessException
  • InstantiationException
  • InterruptedException
  • IOException
  • NoSuchMethodException ParseException
  • PrinterException
  • RuntimeException
  • ArithmeticException
  • ArrayIndexOutOfBoundsException
  • ArrayStoreException
  • ClassCastException
  • ClassNotFoundException
  • IllegalAccessException
  • IllegalArgumentException
  • IndexOutOfBoundsException
  • NegativeArraySizeException
  • NullPointerException
  • NumberFormatException
  • RuntimeException
  • SecurityException
  • ...

14
Exception Class Hierarchy
indicates serious problems that a reasonable
application should not try to catch. Most such
errors are abnormal conditions
Object
these exceptions must be explicitly dealt with
Throwable
Exception
Error
other classes ...
other classes ...
RunTimeException
other classes ...
These exceptions do not need to be caught or
declared in throws clause
15
What exceptions are thrown?
  • How do you figure out what exception will be
    thrown that you must handle?
  • read the documentation for the class you are
    using
  • read the documentation about the various
    exception classes
  • One way is simply use the methods I want and let
    the compiler tell me when I missed something!!

16
Example parseInt
  • public static int parseInt(String s, int radix)
  • throws NumberFormatException
  • Parses the string argument as a signed
    integer in the radix specified by the
  • second argument. The characters in the
    string must all be digits of the specified
  • radix (as determined by whether
    Character.digit(char, int) returns a nonnegative
  • value), except that the first character may
    be an ASCII minus sign '-' ('\u002d')
  • to indicate a negative value. The resulting
    integer value is returned.
  • An exception of type NumberFormatException
    is thrown if any of the
  • following situations occurs
  • The first argument is null or is a string of
    length zero.
  • The radix is either smaller than
    Character.MIN_RADIX or larger than
  • Character.MAX_RADIX.
  • Any character of the string is not a digit of
    the specified radix, except that the first
  • character may be a minus sign '-' ('\u002d')
    provided that the string is longer than
  • length 1.
  • The integer value represented by the string is
    not a value of type int.

17
Example CmdLine
public class CmdLine public static void main(
String args ) for ( int i0
iltargs.length i ) int val try
val Integer.parseInt( argsi )
System.out.println( val ) catch
( NumberFormatException e )
System.out.println( "??" )
18
How to write your own exception
  • Exception is class. Thus, my exception must be
    derived from some pre-defined exception class
  • Often the only method you need to define are the
    constructors
  • Include a constructor that takes a String message
    argument
  • Include a default constructor with a call to
    super and default message string

public class MyFirstException extends Exception
public MyFirstException()
public MyFirstException(String message)
super(message)
19
Example how to use your exception
  • public void divide(int numerator, int
    denominator)
  • try
  • if (denominator 0)
  • throw new MyFirstException(Dividing by
    zero is not allowed!!! )
  • quotient numerator/(double)denominator
  • System.out.println(numerator "/"
    denominator " " quotient)
  • catch(MyFirstException e)
  • System.out.println(e.getMessage( ))

20
Example how to use your exception
Methods can throw execptions and not catch them.
This is the most common way to write code!
public double divide(int numerator, int
denominator) throws MyFirstException if
(denominator 0) throw new
MyFirstException( ) return numerator /
(double)denominator
21
Throwing exception, but not catching it
  • When defining a method you must include a
    throws-clause to declare any exception that might
    be thrown but is not caught in the method.
  • Use a throws-clause to "pass the buck" to
    whatever method calls it (pass the responsibility
    for the catch block to the method that calls it)
  • that method can also pass the buck,but
    eventually some method must catch it
  • This tells other methods
  • "If you call me, you must handle any exceptions
    that I throw."

22
Catching the exception
MethodA throws MyException but doesnt catch it.
Must be declared in the throws clause.
MethodB, which calls MethodA, catches MyException
exceptions
public void MethodA() throws MyException .
throw new MyException(Helpful Msg) .
public void MethodB() try
MethodA() catch(MyException e)
ltcode to handle the errorgt
23
Passing the catch
MethodA throws MyException but doesnt catch it.
Must be declared in the throws clause.
MethodB, which calls MethodA, doesnt catch
MyException exceptions. Must be declared in the
throws clause.
public void MethodB() throws MyException
MethodA()
public void MethodA() throws MyException .
throw new MyException(Helpful Msg) .
24
More about passing the catch
  • Good programming practice
  • Every exception thrown should eventually be
    caught
  • If a method throws an exception, it expects the
    catch block to be in that method unless it is
    deferred by a throws-clause
  • if the calling method also defers with a
    throws-clause, its calling program is expected to
    have the catch block, etc., up the line all the
    way to main, until a catch block is found

25
Uncaught exceptions
  • If an exception is not caught in the method that
    throws it or any of its calling methods, either
  • the program ends
  • the program becomes unstable
  • Your main method should never have a throws
    clause!

RunTimeExceptions" do not need a catch block or
throws-clauseyou can break the rules since these
exceptions are not checked.
26
Multiple exceptions andcatch blocks in a method
  • Methods can throw more than one exception
  • The catch blocks immediately following the try
    block are searched in sequence a catcher of the
    appropriate type
  • the first catch block that handles the exception
    type is the only one that executes
  • Specific exceptions are typically derived from
    more general types
  • So put the catch blocks for the more specific
    exceptions early and the more general ones later
Write a Comment
User Comments (0)
About PowerShow.com