DEV Community

darKLoin
darKLoin

Posted on

day-07

Day- 09
Index
01.Exception Handling
02.try and catch
03.Multiple catch

  1. Nested try block ---------------------------------START---------------------------- ----------------------------------01------------------------------
  2. Exception Handling
    ~It is error that are occure during runtime then program is terminate avnormally to stop the termination or handling the exception is done.

    error - occur during compile time
    exception - occur during runtime of program.
    ~we use the following process
    ~~ try - monitor that code ,in wahic exception can occur it is going to have the exception.
    ~~ catch - it is going to handle the exception, which is thrown from by try block.
    ~~ throw - to manually throw a exception{user define}
    ~~ throws - it throws the exception which are generated by the method.
    ~~finally - that we want to excute everytime, even the exception is occur or not

different calss to handle exception
~Throwable - exception[run time], error[compile time]

example 01.1  : program whithout exception handle
Enter fullscreen mode Exit fullscreen mode
class Main
{
    public static void main(String args[])
    {
        int  a = 1245 , k = 0;
        int d = a/0;
    }
}
Enter fullscreen mode Exit fullscreen mode
Exception in thread "main" java.lang.ArithmeticException : / by zero 
    at Main.main(Main.java:6)

Enter fullscreen mode Exit fullscreen mode

---------------------------------END----------------------------
---------------------------------02------------------------------
02.try and catch
~ now using the exception handle try/catch
rules to use:

try: it use to monitor your code for arising exception
catch: it use to handle the exception arise in the try block
syntax:
...
try{
...
}catch(..exception name..)
{
...to handle
}

example: program using the exception handle (try/catch)
Enter fullscreen mode Exit fullscreen mode
class Main
{
    public static void main(String args[])
    {
        int k = 45 , kk = 0 ;
        try{
            int d = k/kk;
            System.out.println("form try block // never execute");
        }catch(ArithmeticException e )//exception name and exception object 'e'
        {
            System.out.println("form catch block after execute try");
        }
        System.out.println("after the catch block ");
    }
}
Enter fullscreen mode Exit fullscreen mode
form catch block after execute try
after the catch block 
Enter fullscreen mode Exit fullscreen mode

~ we can see here that statement in the try block is not execuate once the try block find and exception
NOTE: do not write the try/catch block in a single statement it should follow the above written syntax
example: program each iteration of the for loop obtains two random integers. Those two integers aredivided by each other, and the result is used to divide the value 12345. The final result is put into a. If either division operation causes a divide-by-zero error, it is caught, the value of a is set to zero, and the program continues.

import java.util.*;
class Main
{
    public static void main(String args[])
    {
        int a ;
        Random rr = new Random();
        for(int i = 0 ; i < 100 ; i++)
        {
            int numone = rr.nextInt();
            int numtwo = rr.nextInt();
            try{
                int numthird = numone/numtwo;
                int a = 12345/ numthird;
                // caught by devision as xero
            }catch(ArithmeticException e)
            {
                a = 0 ; // a is set to 10
            }
            System.out.println("a: "+a);
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

~this will example will show the exception handling and continues of the progarm means it only get terminate until its condition satisfied

---------------------------------END----------------------------
---------------------------------03------------------------------

  1. Multiple catch ~ In a program we can have a try block with the multiple catch block when a try block contain more than one exception to handle ~ multiple catch block will work as per the exception define in them. example: progarm having the a that devision is done by zero and a array, size of array is define by the command line argument and another array assigning a value which is out of index of that array.
class Main
{
    public static void main(String args[])
    {
        int a = args.length;
        int c = a+1;
        try{
            int f = c/a;
            int c[] = {1};
            c[33] = 45;
        }catch(ArithmeticException e )//the exception will be this without any commandline argument
        {
            System.out.println("it is from 1st catch ");
            System.out.println(" Devide by zero : "+ e);
        }
        catch(ArrayIndexOutOfBoundsException e )// the exception will be this with command line argument
        {
            System.out.println("it is form 2nd catch");
            System.out.println(" Index of array is out of bound : "+ e);    
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

~while giving the multiple catch block remeber that exception sub-class should be come before the excetion super-class
~if the exception sub-class will come after the exception super-class then the sub-class catch block will not execute
example : program showing the importance of placing super-class exception and sub-class exception

class Main
{/* In java unreachable code is an error */
    public static void main(String args[])
    {
        int a = 0, j , c ;
        int k = a +1;
        try{
            c = k/a;
            int d[] = {41};
            d[4512] = 1;
        }catch(Exception e )
        {
            System.out.println("this is frome Exception super-class "+e);
        }
        catch(ArithmeticException e )//this catch block will never reach because the ArithmeticException is a sub-class of the Exception
        {
            System.out.println("from airthmetic exception "+e);
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

---------------------------------END----------------------------
---------------------------------04------------------------------

  1. Nested try block ~ Nested try are used when catch block does not have the particular exception handler for the exception of try block then try statement's catch handler are inspected for a match. it continues until one of the catch statements succeeds, or until all of the nested try statements are exhausted example : program showing the nested try block
class Main
{
    public static void main(String args[])
    {
        int a = args.length;
        try{
            int l = 5;
            l = l/a;//devide by zero exception
            System.out.println("a :"+a);
            try{
                if(a == 1)
                    a = a/a-a;// devide by zero   

                if(a == 2)
                {
                    int c[] = {44};
                    c[451] = 1;//array index boundation
                }
            }catch(ArrayIndexOutOfBoundsException)
            {
                System.out.println("array index problem... : "+e);
            }               
        }catch(ArithmeticException e)
        {
            System.out.println("airthmetic exception first catch : "+e);
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

---------------------------------END----------------------------
---------------------------------05------------------------------

  1. throw
    ~it allow to create and throw the exception explicitly
    ~exception thrown can be done by two ways
    1. creating our own throw statment
    2. using parameter in catch statement
    ~onece the thorw statement encounctered then the all code after throw will not execute
    ~the try exception inspecte the enclose catch statement for matching if matched then control transfer to that and if not hen inspecte the next try statement and so on if there is no matching catch is available then it transfer to default excepton handler.

    example: program contain user created throw statement for handle

class Main
{
    static void throwexp()
    {
        try{
            throw new NullPointerException("hello");
        }catch(NullPointerException e)
        {
            System.out.println("caught throw hello form throwexp");
            throw e;
        }
    }

    public static void main(String args[])
    {
        try{
            throwexp();
        }catch(NullPointerException e)
        {
            System.out.println("again caught throw hello from MAIN");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

---------------------------------END----------------------------
---------------------------------06------------------------------

  1. throws
    ~when method causing an exception that cannot handle then it must specified this behavior
    ~behavior is specified by including the 'throws' clause in the declaretion of method
    all type of exceptions that method might throw must br declared in throws clause
    like
    type method_name(parameter) throws exception list
    {
    ....
    }

    example : program contain the throws statement

class Main
{
    static void throwscheck() throws IllegalAccessException
    {
        System.out.println("inside throwscheck");
        throw new IllegalAccessException("throwName");
    }

    public static void main(String args[])
    {
        try{
            throwscheck();
        }catch(IllegalAccessException e )
        {
            System.out.println("inside Main catch \n caught : "+e);
        }
    }

}
Enter fullscreen mode Exit fullscreen mode

---------------------------------END----------------------------
---------------------------------07------------------------------
07.finally
~it is used to bypass the exception-handling mechanism and execute the reamain code...
~finally block will execute weather or not exception is thrown
~when an exception is throw then the finally block will execute even no catch statement matches the exception
~when there is uncaught exceotion or explicit return statement then the finally clause execute just before the method returns.
~the finally clause is optional, it help when there is a exception in mid of file and to skip the abnoraml termination we use the finally keyword.
example : program showing the all three above written use of finally

class Main {
    static void classA() {
        try {
            System.out.println("from classA try, no return, yes exception");
            throw new RuntimeException("runtime");
        } finally {
            System.out.println("from classA finally");
        }
    }

    static void classB() {
        try {
            System.out.println("from classB try, return , no exception");
            return;
        } finally {
            System.out.println("from classB finally");
        }
    }

    static void classC()
    {
        try{
            System.out.println("from classC try, no return, no exception");
        }finally
        {   
            System.out.println(" from classC finally");
        }
    }

    public static void main(String args[]) {
        try {
            classA();
        } catch (RuntimeException e) {
            System.out.println("caught classA e:" + e);
        }
        classB();
        classC();
    }
}
Enter fullscreen mode Exit fullscreen mode

---------------------------------END----------------------------
---------------------------------08------------------------------
08.Creating own Exception Sub-class
~When we want to create a own exception to handle the situation specific to your application and program
~it is done by just creating the sub-class of Exception and sub-class should be a sub-class of Throwable
~it inherit the method provided by the Throwable, and Exception does not define the method of its own

example :
Enter fullscreen mode Exit fullscreen mode
class ownException extends Exception {
    private int detail;

    ownException(int a) {
        detail = a;
    }

    public String toString() {
        return "OwnException[" + detail + "]";
    }
}

class Main {
    static void compute(int a) throws ownException {
        System.out.println("Called compute(" + a + ")");
        if (a > 10)
            throw new ownException(a);
        System.out.println("Normal exit.");
    }

    public static void main(String args[]) {
        try {
            compute(1);
            compute(20);
        } catch (ownException e) {
            System.out.println("Caught " + e);
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)