The throw keyword is used to create exception object explicitly and throw it to JVM.
throw new ArithmeticException("don't divide by zero");
The main objective of throw keyword is used to create exception object and handover to JVM.
It is mainly used to create customized exceptions.
Case-1: using throw keyword
public class Test {
public static void main(String[] args) {
throw new ArithmeticException("don't divide by zero");
System.out.println("Hello world");//unreachable code
}
}
In this case, we will get compile time error because after throw any exception object we can not write the code and compiler won’t accept it.
It will give the output as
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Unreachable code
at com.exceptions.Test.main(Test.java:5)
Case-2: throw only throwable types
We can throw only throwable types not all the objects. We can not throw normal java class object, if we throw normal java class object then we will get compile time error.
In the below program Test class extends RuntimeException so we can throw Test class object by using throw keyword.
public class Test extends RuntimeException{
public static void main(String[] args) {
throw new Test();
}
}
Exception in thread "main" com.exceptions.Test
at com.exceptions.Test.main(Test.java:4)
Example of throw keyword
public class Test{
static void pay(int amount){
if(amount<1000){
throw new ArithmeticException("you have less amount");
}
else{
System.out.println("your paid");
}
}
public static void main(String[] args) {
pay(800);
System.out.println("main task completed");
}
}
Exception in thread "main" java.lang.ArithmeticException: you have less amount
at com.exceptions.Test.pay(Test.java:5)
at com.exceptions.Test.main(Test.java:13)
if we replace with the pay(1000) instead of pay(800) then it will give output as
your paid
main task completed
No comments:
Post a Comment