java throw keyword:-
throw keyword used to create our own exception object explicitly and we can handover this (our own created) exception object to JVM manually.
example:-
The main objective of throw keyword is to hand over our created exception object to JVM manually.
Let's take two example where the output will be same.
Example 1:-
class Test
{
public static void main(String[] args)
{
System.out.println(10/0);
}
}
Output is:-
In the above program main() method is responsible for creating the exception object and handing over to JVM.
Example 2:-
class Test
{
public static void main(String[] args)
{
throw new ArithmeticException("/ by zero");
}
}
Output is:-
In the above case, the programmer is responsible for creating the exception object and handing over to JVM manually.
Note: throw keyword is the best choice for user defined exceptions or customized exceptions.
Important LoopHole:-
1. After the throw statement, we are not allowed to write any statement directly otherwise, we will get Compile time error saying"Unreachable statement."
example 3:-
class Test
{
public static void main(String[] args)
{
throw new ArithmeticException("/ by zero");
System.out.println("javabychetan");
}
}
Compile Time Error
2. We can use throw keyword only for Throwable types (which extends Throwable class ) only. If we are trying for normal java objects then we will get compile time error saying"incompatible types".
example 4.
class Test
{
public static void main(String[] args)
{
throw new Test();
}
}
Compile Time Error
No comments:
Post a Comment
Be the first to comment!
Don't just read and walk away, Your Feedback Is Always Appreciated. I will try to reply to your queries as soon as time allows.
Note:
1. If your question is unrelated to this article, please use our Facebook Page.
2. Please always make use of your name in the comment box instead of anonymous so that i can respond to you through your name and don't make use of Names such as "Admin" or "ADMIN" if you want your Comment to be published.
Regards,
JavaByChetan
Back To Home