KEMBAR78
Java Throw Throws | PDF
0% found this document useful (0 votes)
3 views8 pages

Java Throw Throws

Uploaded by

Sinduja Baskaran
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views8 pages

Java Throw Throws

Uploaded by

Sinduja Baskaran
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

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

You might also like