Throwing Exceptions Example

This program demonstrates the use of throw keyword.

Problem Statement

Write a Java program that throws an exception explicitly using throw.

Source Code

1 public class ThrowKeywordExample {
2 public static void main(String[] args) {
3 System.out.println("Eduinq Throw Keyword Example");
4 try {
5 validateAge(15);
6 } catch(Exception e) {
7 System.out.println("Eduinq Exception: "+e.getMessage());
8 }
9 }
10 static void validateAge(int age) throws Exception {
11 if(age<18) throw new Exception("Age must be 18 or above");
12 else System.out.println("Eduinq Age Validated");
13 }
14 }

Program Output

					Eduinq Throw Keyword Example
Eduinq Exception: Age must be 18 or above
				

Explanation

The throw keyword is used to explicitly throw exceptions. - Custom validation logic triggers exception when condition fails. - Catch block handles the thrown exception gracefully. - This design improves input validation and error reporting. - In enterprise systems, throw keyword ensures strict rule enforcement. Conclusion: Shows explicit throwing of exceptions using throw keyword.

Quick Links to Explore