+ All Categories
Home > Documents > Except Modified

Except Modified

Date post: 07-Apr-2018
Category:
Upload: nadisha-fathima
View: 223 times
Download: 0 times
Share this document with a friend

of 45

Transcript
  • 8/6/2019 Except Modified

    1/45

    Sabeena Java

    chintech Unit-1

    Exception

    An exception is an event that occurs duringthe execution of a program that disrupts thenormal flow of instructions.

    Java handles exceptions using fivekeywords try, catch, finally, throws,throw.

    Programming errors User/environmental errors System errors

  • 8/6/2019 Except Modified

    2/45

    Sabeena Java

    chintech Unit-1

    A Java exception is an object that describesan exceptional condition that has occurred ina piece of code.

    When an exceptional condition arises,

    an object representing that exception iscreated and

    thrown in the method that caused theerror.

  • 8/6/2019 Except Modified

    3/45

    Sabeena Java

    chintech Unit-1

    An exception can be caught to handle it orpass it on.

    Exceptions can be generated by the Java run-time system, or they can be manuallygenerated by your code.

  • 8/6/2019 Except Modified

    4/45

  • 8/6/2019 Except Modified

    5/45

    Sabeena Java

    chintech Unit-1

    Object

    Class Object is the root of the classhierarchy.

    Every class has Object as a superclass.

    All objects, including arrays, implement themethods of this class.

    The Object class provides several methodsthat can be useful to any of its subclasses.

  • 8/6/2019 Except Modified

    6/45

    Sabeena Java

    chintech Unit-1

    public class Test

    {

    ...

    }

    is equivalent to

    public class Test extends Object

    {...

    }

  • 8/6/2019 Except Modified

    7/45

    Sabeena Java

    chintech Unit-1

    clone() - used to make copies of an object -

    equals(Object o) - used to test whether the object is equal to

    o. The default is that they both point to the same object Thismethod is often overriden.

    toString() - provide a string representation of this object.Defualt is a string consisting of

    name of the class + @ + hash code

    (where the hash code is in hex format) of the object. Usuallyoverriden to provide more information.

    finalize() - called by the garbage collector when there are nomore references to this object.

    getClass() - gets the runtime class name of the object

    hashCode() - generate a hash code value unique for this

  • 8/6/2019 Except Modified

    8/45

    Sabeena Java

    chintech Unit-1

    The fololwing can only be called from within a synchronized method:

    notify() - called by a thread that owns this object's lock to tell awaiting thread, as arbitrarily chosen by the VM, that the lock is nowavailable.

    notifyAll() - similar to notify() but wakes all waiting threads and thenthey compete as usual for the lock.

    wait() - the thread that owns the lock on this object will release thelock and then wait for a notify() or notifyAll() to get the lock back.

    wait(long msecs) - same as wait() but if no notify comes within thespecified time, it wakes up and starts competing for the lock on thisobject.

    wait(long msecs, int nanosecs) - same as wait(long msecs) butspecified to the nanosec.

  • 8/6/2019 Except Modified

    9/45

    Sabeena Java

    chintech Unit-1

    The Throwable class

    The Throwable class is the superclass of allerrors and exceptions in the Java language.

    Only objects that are instances of thisclass (or one of its subclasses) are thrownby the Java Virtual Machine or can bethrown by the Java throw statement.

    Similarly, only this class or one of itssubclasses can be the argument type in acatch clause.

  • 8/6/2019 Except Modified

    10/45

    Sabeena Java

    chintech Unit-1

    class Exception

    The class Exception represents exceptionsthat

    a program faces due to abnormal or

    special conditions during execution. Exceptions can be of 2 types:

    Checked (Compile time Exceptions) Unchecked (Run time Exceptions).

  • 8/6/2019 Except Modified

    11/45

    Sabeena Java

    chintech Unit-1

    Runtime exceptions

    Runtime exceptions represent programmingerrors that manifest at runtime.

    For exampleArrayIndexOutOfBounds,NullPointerException and so on.

  • 8/6/2019 Except Modified

    12/45

    Sabeena Java

    chintech Unit-1

    Error

    Errors are irrecoverable conditions thatcan never be caught.

    Example: Memory leak, LinkageError etc.Errors are direct subclass of Throwableclass.

  • 8/6/2019 Except Modified

    13/45

    Sabeena Java

    chintech Unit-1

    Program statements that you want tomonitor for exceptions are contained withina try block.

    If an exception occurs within a try block, it

    is thrown.

    Code within catch block catch theexception and handle it .

    System generated exceptions areautomatically thrown by the Java run-time

    system

  • 8/6/2019 Except Modified

    14/45

    Sabeena Java

    chintech Unit-1

    To manually throw an exception, use the

    keyword throw

    Any exception that is thrown out of amethod must be specified as such by athrows clause

    Any code that absolutely must be executed

    before a method returns is put in a finallyblock

  • 8/6/2019 Except Modified

    15/45

    Sabeena Java

    chintech Unit-1

    How do you handle exceptions?

    To handle the exception, write a try-catch block.

    To pass the exception up the chain,declare a throws clause in your methodor class declaration.

  • 8/6/2019 Except Modified

    16/45

  • 8/6/2019 Except Modified

    17/45

    Sabeena Java

    chintech Unit-1

    Uncaught Exceptions

    What happens when Exceptions are nothandled?

    class Exec0

    {public static void main(String ar[])

    {

    int a = 42 / 0;

    }} java.lang.ArithmeticException : / by

    zero

    at Exec0.main(Exec0.java:5)

    Output

  • 8/6/2019 Except Modified

    18/45

    Sabeena Java

    chintech Unit-1

    When the Java run-time system detects the

    attempt to divide by zero, it constructs a new exception object and then throws this exception.

    This causes the execution of Exec0 to stop,because once an exception is thrown itmust be caught by exception handler and

    dealt with immediately.

  • 8/6/2019 Except Modified

    19/45

  • 8/6/2019 Except Modified

    20/45

    Sabeena Java

    chintech Unit-1

    The output generated for the above exampleprogram is :

    java.lang.ArithmeticException : / by zero

    at Exec0.main(Exec0.java:5)Here Exec0 ----> the class name

    main -----> the method name

    Exec0.java ----> the file name.

    5 -----> the line number

    ArithmeticException ---> a type of exception

  • 8/6/2019 Except Modified

    21/45

  • 8/6/2019 Except Modified

    22/45

    Sabeena Java

    chintech Unit-1

    Using try and catchclass Exec2{

    public static void main(String ar[]){

    int a;try{

    a=32/0;System.out.println( This will not be printed\n);

    }catch(ArithmeticException e){System.out.println(\n Division by zero\n);

    System.out.println(\n Exception caught = +e);}

    System.out.println(\n After catch statement\n);

    }}

  • 8/6/2019 Except Modified

    23/45

    Sabeena Java

    chintech Unit-1

    Multiple Catch Clausesclass multicatch{

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

    int a = ar.length;System.out.println("a = "+a);int b = 42/a;int c[]={1}; c[42]=99;

    }catch(ArithmeticException e){

    System.out.println("Divide by 0 : "+e);}catch(ArrayIndexOutOfBoundsException e){

    System.out.println("Array Index Out Of Bounds : "+e);

    }} }

  • 8/6/2019 Except Modified

    24/45

    Sabeena Java

    chintech Unit-1

    Unreachable Code Error

    When multiple catch statements are

    used , it is important to remember thatexception subclasses must come before anyof their superclasses.

    This is because a catch statement that usesa superclass will catch exceptions of thattype plus any of its subclasses.

    Thus, a subclass would never be reached ifit came after its superclass.

    In Java, unreachable code is an error.

    Error !!!

  • 8/6/2019 Except Modified

    25/45

    Sabeena Java

    chintech Unit-1

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

    try {int a = 0;int b = 42 / a;

    }

    catch(Exception e) {System.out.println("Generic Exception catch.");}

    catch(ArithmeticException e) { // ERROR -unreachable

    System.out.println("This is never reached.");}

    }}

    Error !!!

  • 8/6/2019 Except Modified

    26/45

    Sabeena Java

    chintech Unit-1

    throw

    It is possible for program to throw anexception explicitly, using the throwstatement.

    The general form of throw is throw ThrowableInstance

    ThrowableInstance must be an object oftype Throwable or a subclass of Throwable.

    There are two ways to obtain a Throwableobjects: Using a parameter into a catch clause

    Creating one with the newoperator

  • 8/6/2019 Except Modified

    27/45

    Sabeena Java

    chintech Unit-1

    class throwdemo{

    static void demoproc()

    {try{

    throw new NullPointerException("demo");}

    catch(NullPointerException e){

    System.out.println("Caught within demoproc() ");throw e;

    }}

    Exception Re-thrown

  • 8/6/2019 Except Modified

    28/45

    Sabeena Java

    chintech Unit-1

    public static void main(String ar[]){

    try{

    demoproc();}

    catch(NullPointerException e){

    System.out.println("\n Recaught : "+e);}

    }} OUTPUT

    Caught within demoproc.Recaught: java.lang.NullPointerException: demo

  • 8/6/2019 Except Modified

    29/45

    Sabeena Java

    chintech Unit-1

    throw new NullPointerException("demo");

    new is used to construct an instance ofNullPointerException.

    All of Java's built-in run-time exceptions have at

    least 2 constructors :one with no parameter and

    one that takes a string parameter.

  • 8/6/2019 Except Modified

    30/45

  • 8/6/2019 Except Modified

    31/45

    Sabeena Java

    chintech Unit-1

    A throws clause lists the types ofexceptions that a method might throw.

    This is necessary for all exceptions, exceptthose of type Error or RuntimeException,or any of their subclasses.

    All other exceptions that a method canthrow must be declared in the throws

    clause.

    If they are not, a compile-time error willresult.

  • 8/6/2019 Except Modified

    32/45

    Sabeena Java

    chintech Unit-1

    throws - Syntax

    This is the general form of a methoddeclaration that includes a throws clause:

    type method-name(parameter-list) throws

    exception-list{

    // body of method

    }

  • 8/6/2019 Except Modified

    33/45

    Sabeena Java

    chintech Unit-1

    // This program contains an error and will notcompile.

    class ThrowsDemo {static void throwOne() {System.out.println("Inside throwOne.");throw new IllegalAccessException("demo");

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

    }}

    ThrowsError.java:5: unreported exceptionjava.lang.IllegalAccessException; must be caught or declared tobe thrown

    throw new IllegalAccessException("demo");^

    1 error

    Output

    Program Containing Error

  • 8/6/2019 Except Modified

    34/45

    Sabeena Java

    chintech Unit-1

    To make this example compile, you needto make two changes.

    First, you need to declare that throwOne( )throws IllegalAccessException.

    Second, main( ) must define a try/catchstatement that catches this exception.

  • 8/6/2019 Except Modified

    35/45

    Sabeena Java

    chintech Unit-1

    class ThrowsDemo {static void throwOne() throws IllegalAccessException

    {System.out.println("Inside throwOne.");

    throw new IllegalAccessException("demo");}public static void main(String args[]) {

    try {throwOne();

    } catch (IllegalAccessException e) {System.out.println("Caught " + e);

    }}

    }

    Correct - Program

  • 8/6/2019 Except Modified

    36/45

    Sabeena Java

    chintech Unit-1

    finally

    finally creates a block of code that will be

    executed after a try/catch block hascompleted and before the code following thetry/catch block.

    The finally block will execute whether or notan exception is thrown.

    If an exception is thrown, the finally blockwill execute even if no catch statementmatches the exception.

  • 8/6/2019 Except Modified

    37/45

    static void procB() {

  • 8/6/2019 Except Modified

    38/45

    Sabeena Java

    chintech Unit-1

    static void procB() {try {System.out.println("inside procB");return;

    }finally {

    System.out.println("procB's finally");}

    }

    static void procC() {try {

    System.out.println("inside procC");

    }finally {

    System.out.println("procC's finally");}

    }

  • 8/6/2019 Except Modified

    39/45

    Sabeena Java

    chintech Unit-1

    public static void main(String args[]) {

    try {procA();

    }catch (Exception e) {

    System.out.println("Exception caught");}

    procB();procC();

    }}

    inside procAprocAs finally

    Exception caughtinside procBprocBs finallyinside procC

    procCs finally

    Output

  • 8/6/2019 Except Modified

    40/45

    Sabeena Java

    chintech Unit-1

    In this example,

    procA( ) prematurely breaks out of the tryby throwing an exception. The finallyclause is executed on the way out.

    procB( )s try statement is exited via areturn statement. The finally clause isexecuted before procB( ) returns.

    In procC( ), the try statement executes

    normally, without error. However, thefinally block is still executed.

    J B il i E i

  • 8/6/2019 Except Modified

    41/45

    Sabeena Java

    chintech Unit-1

    Javas Built-in Exceptions

    Inside the standard package java.lang,Java defines several exception classes.

    Unchecked Exception

    Checked Exception

    U h k d E i

  • 8/6/2019 Except Modified

    42/45

    Sabeena Java

    chintech Unit-1

    Unchecked Exception

    NumberFormatExceptionNullPointerExceptionNegativeArraySizeExceptionIndexOutOfBoundsExceptionIllegalstateException

    IllegalMonitorStateExceptionIllegalArgumentExceptionClassCastExceptionArrayStoreExceptionArrayIndexOutOfBoundsExceptionArithmeticExceptionSecurityException

  • 8/6/2019 Except Modified

    43/45

  • 8/6/2019 Except Modified

    44/45

    class ExceptionDemo {

  • 8/6/2019 Except Modified

    45/45

    class ExceptionDemo { static void compute(int a) throws MyException { System.out.println("Called compute(" + a + ")");

    if(a > 10)throw new MyException(a);System.out.println("Normal exit");

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

    try {compute(1);

    compute(20);}

    catch (MyException e) {System.out.println("Caught " + e);

    }}


Recommended