Use of Throws and Throw in Exceptional Handling

 
Throws keyword is used to declare an exception. When programmer do not want to handle exception, it will declare the exception and pass to Caller method. Callermethod will handle these exception.
e.g.
void methodName throws ExceptionClass_type(){ ........ }
 
Throw keyword is used to throw Exception in java.
e.g.
void methodName throws ExceptionClass_type(){
throw new IOException("Resourse is not found");
}

Let's see below programme

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class SuperThrowsClass
    {
        void method1() throws ArrayIndexOutOfBoundsException
            {
                int a[] = new int[3];
                System.out.println(a[3]);
                System.out.println("thros");
            }
    }
public class ThrowsClass extends SuperThrowsClass
    {
        public static void main(String[] args)
            {
                SuperThrowsClass sc = new SuperThrowsClass();
                sc.method1();
                System.out.println("Rest code of the programme...");
            }
    }

O/P:

 java throw keywords

Since method1() of SuperThrowsClass throws the exception ,so that who ever is calling this method has to handle the exception.

But ThrowsClass main() method also not handled the exception thats why programme is terminating in between.So,if some method do not want to handle the exception it will throw the exception by using keyword "throws".

See the below example where caller method(main method of ThrowsClass) handles the exception

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class SuperThrowsClass
    {
    void method1() throws ArrayIndexOutOfBoundsException
        {
            int a[] = new int[3];
            System.out.println(a[3]);
            System.out.println("throws");
        }
    }
public class ThrowsClass extends SuperThrowsClass
    {
        public static void main(String[] args)
            {
                SuperThrowsClass sc = new SuperThrowsClass();
                try
                    {
                        sc.method1();
                    }
                catch (ArrayIndexOutOfBoundsException ae)
                    {
                        System.out.println("exception caught" + ae);
                    }
                System.out.println("Rest code of the programme...");
            }
    }

O/P:

java throw keyword

 

NOTE:

Difference between throw & throws in Exception Handling

1. You can decalre multiple Exception by using "throws" keyword ,but using "throw" keyword only one instacne.
e.g
void method throws FirstExceptiontype,SecondExceptiontype()
{
}
void method throws FirstExceptiontype(){
throw new FirstExceptiontype("..");
}
2. Throws keyword can be used in method signature only, throw can be used anywhere inside method.
3. Throw keyword can be used as break statement in switch cases.