Example using throw and throws

First of all we define here the keywords throw and throws as:
throw: It is used to  throw the exception in your own way. Generally JVM will identify the exception class, create the object and throw that object. Sometimes you may get a chance to do this  specially in the case of user defined exceptions.
throws :Throws keyword is used to specify the method level exception.
Generally when you are implementing a method, code inside that method may rise exceptions.If you want to handle the exception in the same method then use try and catch method.


Now we show the example using the throw and throws. We defined three classes-UserException.java, Aclass.java,Bclass.java and TestThrowandthrows.java.




Here we can see one bye one all classes.


UserException.java




package com.javaforecast4u;
import java.io.*;
public class UserException extends IOException {

}

Aclass.java

package com.javaforecast4u;
import java.io.*;
public class Aclass {
    void method1(int a) throws IOException, ArithmeticException{
         if(a==1){
             throw new ArithmeticException();
         }
         else{
             throw new IOException();
         }
    }
}

 Bclass.java 
package com.javaforecast4u;
import java.io.*;
public class Bclass extends Aclass {
    public void method1(int a){
         System.out.println("Bclass---method1");
    }
}

TestThrowandthrows.java 

package com.javaforecast4u;

import java.io.IOException;

public class TestThrowandthrows {
    public static void main(String arg[])throws IOException, ArithmeticException
    {
    Aclass a=new Bclass();
    a.method1(2);
    }
}



1 comment :

  1. Here I didnt see any use of UserException.

    ReplyDelete