Throw and Throws
The throw Keyword
• • The 'throw' keyword is used to explicitly
throw an exception.
• Throw keyword is used within a method
• • Only one exception can be thrown at a time.
• • Syntax:
• throw new ExceptionType("message");
Example: throw
• public class ThrowExample
• {
• public static void main(String[] args) {
• int age = 15;
• if(age < 18) {
• throw new ArithmeticException("Not eligible to vote");
• }
• else {
• System.out.println("Eligible to vote");
• }
• }
• }
• Output: Exception in thread "main"
java.lang.ArithmeticException: Not eligible to vote
The throws Keyword
• • The 'throws' keyword is used to declare
exceptions.
• • When a method wants to throw an
exception then throws is used.
• • Multiple exceptions can be declared.
• • Syntax:
• returnType methodName() throws
Exception1, Exception2 {...}
Example: throws
Difference: throw vs throws
• • throw:
• - Used to actually throw an exception.
• - Only one exception can be thrown.
• • throws:
• - Used to declare possible exceptions.
• - Multiple exceptions can be declared.
Java Built-in Exceptions
• • ArithmeticException
• • NullPointerException
• • ArrayIndexOutOfBoundsException
• • NumberFormatException
• • IOException
• • FileNotFoundException
• • ClassNotFoundException
• • InterruptedException
User Defined Exception