Throws Keyword Example in Java
10:58:00
As we know
that there are two types of exception – checked and
unchecked. Checked exceptions (compile time) are the one which
forces the programmer to handle it, without which the program doesn’t compile
successfully. While unchecked exception (Runtime) doesn’t get checked during
compilation. “Throws keyword”
is mainly used for handling checked exception as using throws we can declare
multiple exceptions in one go. Let’s understand this with the help of an
example.
Example of throws Keyword
In this example
the method “mymethod” is throwing two checked exceptions so we have declared those exceptions in
the method signature using throws Keyword. If we do not declare
these exceptions then the program will throw a compilation error.
package beginnersbook.com;
import java.io.*;
public class ThrowExample {
void mymethod(int num)throws IOException, ClassNotFoundException{
if(num==1)
throw new IOException("Exception Message1");
else
throw new ClassNotFoundException("Exception Message2");
}
}
class Demo{
public static void main(String args[]){
try{
ThrowExample obj=new ThrowExample();
obj.mymethod(1);
}catch(Exception ex){
System.out.println(ex);
}
}
}
Output:
java.io.IOException: Exception Message1
Since we passed
the argument as 1 during the function call, the program thrown IOException.
0 comments
Thanks for intrest.. We will touch withbyou soon..