If the age is below 18, throw an exception displaying “Access denied”. If the age is 18 or older, print “Access granted”.
public
|
The throw keyword facilitates the creation of custom errors.
It is employed alongside an exception type, with various exception types accessible in Java such as ArithmeticException, ClassNotFoundException, ArrayIndexOutOfBoundsException, SecurityException, and more.
This exception type is frequently utilized in conjunction with a custom method, as illustrated in the example above.
Differences between throw
and throws:
throw |
throws |
employed to raise an exception within a method |
It’s used to specify the type of exception that a method may throw. |
It’s not possible to throw multiple exceptions. |
It’s possible to declare multiple exceptions. |
Syntax
|
Syntax
|