Throw
The throw keyword is used to create a custom error. It's run time exception. We use throw keyword create a user define exception and pass throw the object.
The throw statement is used together with an exception type.
There are many exception types available in Java : ArithmeticException , ClassNotFoundException , ArrayIndexOutOfoundException , SecurityException etc.
throw new UserException();
}
catch(UserException e){
System.out.println("User Define Exception");
}
class UserException extends Exception{
String s=null;
UserException(int i,int j){
s=i + "is less then" + j;
}
public String toString(){
return s;
}
}
class Demo{
public static void main(String []arr){
int i,j;
Scanner sc=new Scanner(System.in);
System.out.print("Enter value of i = ");
i=sc.nextInt();
System.out.print("Enter value of j = ");
j=sc.nextInt();
if(i<j){
try{
throw new UserException(i,j);
}
catch(UserException e){
System.out.println("User Define Exception");
}
}
else{
try{
System.out.println(i/j);
}
catch(ArithmeticException e){
System.out.println("Divide By Zero");
}
}
}
}
Enter value of i = 4Enter value of j = 5User Define ExceptionEnter value of i = 4Enter value of j = 51 Divide by Zero
Throws
The throws keyword indicates what exception type may be thrown by a method. The caller to these methods has to handle the exception using a try-catch block. It's exception handle in higher code. It's compiler time exception.
There are many exception types available in Java: ArithmeticException , ClassNotFoundException , ArrayIndexOutOfoundException , SecurityException etc.
import java.io.*;
public class Throws{
public static void main(String []arr)throws IOException{
int i;
i=System.in.read();
System.out.print((char)i);
}}
Input - 456charOutput - 4
import java.io.*;public class Throws1{public void display()throws IOException{int i;i=System.in.read();System.out.print((char)i);}public static void main(String []arr)throws IOException{Throws1 d=new Throws1();d.display();}}
Input - char456Output - c
0 Comments