Exception Handle
Exception Handle
throws ArithmeticException;
3. Throw keyword is used in the method body to throw an exception, while
throws is used in method signature to declare the exceptions that can occur in
the statements present in the method.
For example:
Throw:
...
void myMethod() {
try {
//throwing arithmetic exception using throw
throw new ArithmeticException("Something went wrong!!");
}
catch (Exception exp) {
System.out.println("Error: "+exp.getMessage());
}
}
...
Throws:
...
//Declaring arithmetic exception using throws
void sample() throws ArithmeticException{
//Statements
}
...
4. You can throw one exception at a time but you can handle multiple
exceptions by declaring them using throws keyword.
For example:
Throw:
void myMethod() {
//Throwing single exception using throw
throw new ArithmeticException("An integer should not be divided by zero!!");
}
..
Throws:
Throw Example
To understand this example you should know what is throw keyword and how
it works, refer this guide: throw keyword in java.
Throws Example
To understand this example you should know what is throws clause and how it
is used in method declaration for exception handling, refer this guide: throws
in java.