If a method is throwing a checked exception, it should either be surrounded by a try catch block to catch it or that method should have the throws clause in its signature . Without the throws clause in the signature the Java compiler does not know what to do with the exception. The throws clause tells the compiler that this particular exception would be handled by the calling method.
Let us take one method divide, here we are throwing a user-defined exception if the second parameter is zero.
static int divide(int first, int second) {
if (second == 0)
throw new MyException("can't be divided by zero");
return first / second;
}
In the above method you can handle the exception in two ways.
1) surround the code with a try-catch block.
static int divide(int first, int second) {
if (second == 0)
try {
throw new MyException("can't be divided by zero");
} catch (MyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return first / second;
}
2) add throws clause in the method signature
If the divide method doesn't catch the checked exceptions that can occur within it, the divide method must specify that it can throw these exceptions. Let's
To specify that divide can throw one exception, add a
throws
clause to the method declaration for the divide method. The throws
clause comprises the throws
keyword followed by a comma-separated list of all the exceptions thrown by that method. The clause goes after the method name and argument list and before the brace that defines the scope of the method; here's an example.static int divide(int first, int second) throws MyException {
if (second == 0)
throw new MyException("can't be divided by zero");
return first / second;
}
No comments:
Post a Comment