Exception
Propagation:
Sending exception from one method to another method is
called exception propagation
Here propagation is nothing but sending.
So guys what is the
situation when we are going to implement this propagation concept?
Answer to this question is when we throw an exception, if it
is not caught in that method it is propagated to another method and interesting
thing is that we don’t need to do anything in this process we just need to
throw an exception that’s it.
Rule:
If the propagated
exception is checked exception then not only current method developer but also
method’s caller method developer should caught or report that checked exception
else it leads to same compiler exception….CE: Unreported Exception
So according to that basic rule is “If checked exception is
raised the method either directly by using throw keyword or indirectly by a
method call it must be caught or reported.
void m1() throws ClassNotFoundException{
throw new ClassNotFoundException();
// direct raising
}
void m2(){
m1(); // Indirect raising
}
Output: Compiler Error
void m3() throws ClassNotFoundException{
m1(); //indirect
raising
}
Output: Compiled
successfully.
Differences between
throw and throws keyword
throw
|
throws
|
It is used to raise and throw exception manually or explicitly by
developer
|
It is used to report that exception to this method caller
|
throw should follow exception object
|
throws should follow exception class name
|
It can raise and throw only one exception at a time
|
It can report multiple exceptions those raising or throwing from
current method with “,” separator
|
It is appeared or used only in a method logic
|
It is appeared or used only in method prototype after method
signature
|
Rules:
1.
After throw and throws keyword only Throwable type class object and name is
allowed. If we pass non-throwable object it leads to CE: incompatible types exception.
2.
If we interchange these keywords places it leads
to CE: illegal start of expression
e.g.
void method1(){
throw “abc”;
}
Output: CE:
Incompatible Types
void method2() throws Integer{
}
Output: Incompatible
Types
void method3(){
throws
new Exception();
}
Output: CE: Illegal
start of Expression
Rule on throw
keyword:
After throw statement we are not allowed to place any java
statement directly, it leads to CE:
Unreachable statement because “throw”
keyword transfers the flow of execution and gives output as exception. So if we
write any code after throw statement it is obviously doesn’t make any sense.
e.g.:
void method1(){
System.out.println(“Hello”);
throw new ArithmeticException();
System.out.println(“Hi”);
}
Output: CE:
Unreachable Statement
So If needed how can
we place statement after throw keyword?
We must place throw keyword in if condition
e.g.
void method1( int a ){
System.out.println(“Hi);
If(a == 10){
Throw
new ArithmeticException();
}
System.out.println(“Input
Value=”+a);
}
Thank You….!!!
Comments
Post a Comment