0% found this document useful (0 votes)
3 views3 pages

Exception Programs

The document presents a Java class demonstrating the difference between 'throw' and 'throws' in exception handling. It includes a method that checks age and throws an IllegalArgumentException if the age is below 18, and shows how to handle this exception in the main method using try/catch. Additionally, it notes that the caller must handle exceptions either with a try/catch block or by declaring them again with 'throws'.

Uploaded by

vsumadeepthi
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 views3 pages

Exception Programs

The document presents a Java class demonstrating the difference between 'throw' and 'throws' in exception handling. It includes a method that checks age and throws an IllegalArgumentException if the age is below 18, and shows how to handle this exception in the main method using try/catch. Additionally, it notes that the caller must handle exceptions either with a try/catch block or by declaring them again with 'throws'.

Uploaded by

vsumadeepthi
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

public class ThrowVsThrows {

// Method declares that it might throw an exception

static void checkAge(int age) throws IllegalArgumentException {

if (age < 18) {

// Actually throwing the exception

throw new IllegalArgumentException("Age must be 18 or above.");

[Link]("Valid age: " + age);

public static void main(String[] args) {

try {

checkAge(15); // Will throw exception

catch (IllegalArgumentException e) {

[Link]("Exception caught: " + [Link]());

}
2) class ThrowVsThrows {

static void checkAge(int age) throws IllegalArgumentException { // "throws" =

declaration

if (age < 18) {

throw new IllegalArgumentException("Age must be 18 or above."); // "throw" = action

[Link]("Valid age: " + age);

public static void main(String[] args) {

try {

checkAge(15); // will cause exception

} catch (IllegalArgumentException e) {

[Link]("Caught Exception: " + [Link]());

┌────────────────────────────────────────────────────

─────┐

│ Caller (main method) must handle it: │


│ - with try/catch block │

│ - OR declare again using "throws" │

└────────────────────────────────────────────────────

─────┘

You might also like