Reasons to use throw keyword


1. To customize the message display in case of an exception.
Public Exception ();
Public Exception (String msg);
2. To throw user defined exception
throw new MyException(“ Emp is empty”);
3. To re-throw caught exception
throw (e);

Example of 1: customizing message

public class Main {
    public static void main(String[] args) {
        try {
            Scanner s=new Scanner(System.in);
            System.out.println("Enter two no.");
            int a = s.nextInt();
            int b = s.nextInt();
            if(b==0)
                throw new ArithmeticException("divide by zero");
            int c = a / b;
            System.out.println("Result is:" + c);
        } catch (NumberFormatException e) {
            System.out.println("Argument must be Number"+e);
        } catch (ArithmeticException e) {
            System.out.println("Second statement must be non zero"+e);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Invalid number of arguments"+ e);
        }catch(Exception e){
            System.out.println("Some thing wrong."+e);
        }

    }
}


Example of 3: re-throwing exception

public class Main {
    public static int divide(int x, int y) throws Exception{
        try{

            if(y==0)
                throw new ArithmeticException("divide by zero");
            int c = x / y;
            return c;
        }catch(Exception e){
            System.out.println("Excetion is rethrowing..");
            throw(e);
        }
    }
    public static void main(String[] args) {
        try {
            Scanner s=new Scanner(System.in);
            System.out.println("Enter two no.");
            int a = s.nextInt();
            int b = s.nextInt();
            System.out.println(divide(a, b));
        } catch (NumberFormatException e) {
            System.out.println("Argument must be Number"+e);
        } catch (ArithmeticException e) {
            System.out.println(e);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Invalid number of arguments"+ e);
        }catch(Exception e){
            System.out.println("Some thing wrong."+e);
        }

    }
}

No comments:

Post a Comment