Exception Handling in Java-Ishan Ghosh

Embed Size (px)

Citation preview

  • 8/2/2019 Exception Handling in Java-Ishan Ghosh

    1/27

    3/5/12

    NAME:ISHAN GHOSHSTREAM:ELECTRONICS AND COMMUNICATION ENGINEERINGCOLLEGE:KANAD INSTITUTE OF ENGINEERING ANDMANAGEMENT,MANKAR.ROLL NO:O8ECE011,08252003014

    YEAR:2008-2012

  • 8/2/2019 Exception Handling in Java-Ishan Ghosh

    2/27

    3/5/12

    EXCEPTION HANDLINGIN JAVA

  • 8/2/2019 Exception Handling in Java-Ishan Ghosh

    3/27

    3/5/12

    INTRODUCTION

    Errors are a normal part ofprogramming. Some of these errorsare flaws in a program's basic design

    or implementation--these are calledbugs. Other types of errors are notreally bugs; rather, they are the

    result of situations like low memoryor invalid filenames. The way wehandle the second type of errordetermines whether they becomebugs. Java's exception-handling

  • 8/2/2019 Exception Handling in Java-Ishan Ghosh

    4/27

    3/5/12

    WHAT IS AN EXCEPTION?

    As the name implies, an exception isan exceptional condition. Anexception is something out of theordinary. Most often, exceptions are

    used as a way to report errorconditions. Exceptions providenotification of errors and a way to

    handle them. This control structureallows us to specify exactly where tohandle specific types of errors.

  • 8/2/2019 Exception Handling in Java-Ishan Ghosh

    5/27

    3/5/12

    IF EXCEPTIONS THAN?

    The most common means of errorchecking is the function's returnvalue. Consider the problem of

    calculating the retail cost of an itemand displaying it. For this example,the retail cost is twice the wholesale

    cost:

    int retailCost( int wholesale )

    {

    C O G

  • 8/2/2019 Exception Handling in Java-Ishan Ghosh

    6/27

    3/5/12

    THE EXCEPTION HANDLINGTECHNIQUE

    Involves the use of the try, catch,and finally Java keywords. Consists ofseveral steps:

    1. try a block of code that may resultin an exception being "thrown"

    2. Code one or more blocks designed

    to automatically catch and handle aspecific type of exception if oneoccurs. At most, only one of theseblocks can be called in a single passthrough the code. If none of the

  • 8/2/2019 Exception Handling in Java-Ishan Ghosh

    7/27

    3/5/12

    syntax: try

    {statements that may result in anexception being thrown;}

    catch (exception-type1 reference){

    statements to handle the exception;}

    catch (exception-type2 reference)

  • 8/2/2019 Exception Handling in Java-Ishan Ghosh

    8/27

    3/5/12

    SOME TERMINOLOGY Exception handling can be viewed as

    a nonlocal control structure. When amethod throws an exception, itscaller must determine whether it can

    catch the exception. If the callingmethod can catch the exception, ittakes over and execution continuesin the caller. Java exceptions areclass objects subclassed from

    java.lang.Throwable. Becauseexceptions are class objects, they

    can contain both data and methods.

  • 8/2/2019 Exception Handling in Java-Ishan Ghosh

    9/27

    3/5/12

    THROW AN EXCEPTIONThe method instantiates an object of

    type Exception. The Exceptionconstructor takes a String parameter.

    The string contains a message that

    can be retrieved when the exceptionis caught.

    The throw statement terminates the

    method and gives its caller theopportunity to catch it:

    if( correct > total )

  • 8/2/2019 Exception Handling in Java-Ishan Ghosh

    10/27

    3/5/12

    ,BLOCKS

    To respond to an exception, the call to the method that producesit must be placed within a try block. A try block is a block of code

    beginning with the try keyword followed by a left and right curly brace.Every try block is associated with one or more catch blocks. Here is atry block:

    try{

    // method calls go here}

    If a method is to catch exceptions thrown by the methods it calls,the calls must be placed within a try block. If an exception is thrown, itis handled in a catch block. Different catch blocks handle differenttypes of exceptions. This is a try block and a catch block set up to

    handle exceptions of type Exception:

    try{// method calls go here}

    catch( Exception e ){

  • 8/2/2019 Exception Handling in Java-Ishan Ghosh

    11/27

    3/5/12

    When any method in the try block throws any type of exception,execution of the try block ceases. Program control passes immediately tothe associated catch block.

    If the catch block can handle the given exception type, it takes over.

    If it cannot handle the exception, the exception is passed to the method's

    caller. In an application, this process goes on until a catch block catchesthe exception or the exception reaches the main() method uncaught andcauses the application to terminate.

  • 8/2/2019 Exception Handling in Java-Ishan Ghosh

    12/27

    Click to edit Master subtitle style

    3/5/12

    An example:import java.io.* ;import java.lang.Exception ;

    public class gradeTest{public static void main( String[] args ){try

    {// the second call to passingGrade throws// an excption so the third call never// gets executedSystem.out.println( passingGrade( 60, 80 ) ) ;System.out.println( passingGrade( 75, 0 ) ) ;System.out.println( passingGrade( 90, 100 ) ) ;}

  • 8/2/2019 Exception Handling in Java-Ishan Ghosh

    13/27

    3/5/12

    }

    catch( Exception e ){System.out.println( "Caught exception --" +e.getMessage() ) ;}}static boolean passingGrade( int correct, int total )throws Exception{

    boolean returnCode = false ;if( correct > total ) {throw new Exception( "Invalid values" ) ;}if ( (float)correct / (float)total > 0.70 )

    {returnCode = true ;}return returnCode ;}

  • 8/2/2019 Exception Handling in Java-Ishan Ghosh

    14/27

    3/5/12

    Output

    The second call to passingGrade()fails in this case because the methodchecks to see whether the number ofcorrect responses is less than the

    total responses.

    When passingGrade() throws anexception, control passes to the

    main() method. In the example, thecatch block in main() catches theexception and prints Caught

    exception - Invalid values.

  • 8/2/2019 Exception Handling in Java-Ishan Ghosh

    15/27

    3/5/12

    MULTIPLE CATCH BLOCKS

    In some cases, a method may have

    to catch different types ofexceptions. Java supports multiplecatch blocks. Each catch block must

    specify a different type of exception: try

    {

    // method calls go here}catch( SomeExceptionClass e ){// handle SomeExce tionClass

  • 8/2/2019 Exception Handling in Java-Ishan Ghosh

    16/27

    3/5/12

    A method that ignores exceptionsthrown by the method it calls.

    import java.io.* ;import java.lang.Exception ;public class MultiThrow

    {public static void main( String[] args ){try{fool() ;}

    catch( Exception e )

  • 8/2/2019 Exception Handling in Java-Ishan Ghosh

    17/27

    3/5/12

    A method that catches andrethrows an exception.

    import java.io.* ;import java.lang.Exception ;public class MultiThrowA

    {public static void main( String[] args ){try

    {fool() ;}

    catch( Exception e )

  • 8/2/2019 Exception Handling in Java-Ishan Ghosh

    18/27

    3/5/12

    THE FINALLY CLAUSEJava introduces a new concept in

    exception handling: the finallyclause. The finally clause sets apart ablock of code that is alwaysexecuted.

    Example of a finallyclause:

    import java.io.* ;import java.lang.Exception ;public class MultiThrowFin{public static void main( String[]

    args )

  • 8/2/2019 Exception Handling in Java-Ishan Ghosh

    19/27

    3/5/12

    THE THROWABLE CLASS

    All exceptions in Java are subclassedfrom the class Throwable. If we wantto create your own exception classes,we must subclass Throwable. Most

    Java programs do not have tosubclass their own exceptionclasses. Following is the public

    portion of the class definition ofThrowable:

    public class Throwable

    {

    J ti Th bl

  • 8/2/2019 Exception Handling in Java-Ishan Ghosh

    20/27

    3/5/12

    Java exceptions are Throwableobjects (they are instances of

    Throwable or a subclass of

    Throwable). The Java packagescontain numerous classes that derivefrom Throwable and thus, build a

    hierarchy of Throwable classes.

  • 8/2/2019 Exception Handling in Java-Ishan Ghosh

    21/27

    3/5/12

    TYPES OF EXCEPTIONSThe methods of the Java API and the

    language itself also throwexceptions.

    These exceptions can be divided

    into two classes: Exception andError.

    Both the Exception and Error classes

    are derived fromThrowable.Exception and its

    subclasses are used to indicate

    conditions that may be recoverable.

  • 8/2/2019 Exception Handling in Java-Ishan Ghosh

    22/27

    3/5/12

    EXCEPTION Java.awt Exceptions:

    The AWT classes have membersthat throw one error and twoexceptions:

    AWTException (exception in AWT)

    llegalComponentStateException (a

    component is not in the proper statefor a requested operation)

    AWTErr (error in AWT)

    java.awt.datatransfer Exception:

  • 8/2/2019 Exception Handling in Java-Ishan Ghosh

    23/27

    3/5/12

    java.io Exceptions:

    The classes in the java.io package

    throw a variety of exceptions, Anyclasses that work with I/O are goodcandidates to throw recoverable

    exceptions. For example, activities suchas opening files or writing to files arelikely to fail from time to time. Theclasses of the java.io package do not

    throw errors at all.

    java.lang Exceptions:

    The java.lang package contains much of

  • 8/2/2019 Exception Handling in Java-Ishan Ghosh

    24/27

    3/5/12

    java.rmi Error:

    The Java Remote Method

    Invocation classes allow Javaobjects to exist on remotemachines. These classes throw the

    following error: ServerError (remote server indicates

    error)

    java.rmi Exceptions: Java objects whose methods are

    invoked remotely through RMI may

    throw exceptions.

    java security acl Exceptions:

  • 8/2/2019 Exception Handling in Java-Ishan Ghosh

    25/27

    3/5/12

    java.security.acl Exceptions:

    The Java security access control list API allows Java developers to controlaccess to specific users. The classes of java.security.acl throw thefollowing exceptions:

    ACLNotFoundException (unable to find access control list)

    LastOwnerExcepti (attempt to delete last owner of ACL)

    NotOwnerExcepti (only the owner may modify)

    java.sql Exceptions:

    The Java SQL API throws the following exceptions:

    DataTruncation (unexpected data truncation)

    SQLException (SQL error--contains detailed SQL information)

    SQLWarning (SQL warning)

    java.util Exceptions: The classes of the java.util package throw the following exceptions:

    EmptyStackException (no objects on stack)

    MissingResourceException (resource missing)

    NoSuchElementException (no more objects in collection)

    BUILT IN EXCEPTIONS

  • 8/2/2019 Exception Handling in Java-Ishan Ghosh

    26/27

    3/5/12

    BUILT-IN EXCEPTIONS

    Here application creates amethod and forces it to divide byzero. The method does not have

    to explicitly throw an exceptionbecause the division operatorthrows an exception whenrequired. An example of abuilt-in exception.

    import java.io.* ;

    import java.lang.Exception ;

  • 8/2/2019 Exception Handling in Java-Ishan Ghosh

    27/27

    3/5/12

    Output:

    The output of this application is

    shown here:2/3 = 0Caught exception / by zero The firstcall to div() works fine. The second

    call fails because of the divide-by-zero error. Even though theapplication did not specify it, anexception was thrown--and caught.