Java Program to demonstrate custom exception class .
Objective
Write a Java program to create and throw a Custom Exception class.
Algorithm / Approach
- Create a class
MyExceptionthatextends Exception. - Inside it, create a custom method
show()that prints an error message ("You Can't Vote"). - Create a
Voteclass with a methodinput(int x) throws MyException. - Inside
input(), if the age is less than 18, manuallythrow new MyException();. - In main, prompt for an age, wrap the call to
input()in a try-catch block, and catchMyException.
MyException.java
import java.util.Scanner;
class MyException extends Exception {
void show() {
System.out.print("You Can't Vote ");
}
}
class Vote {
void input(int x)throws MyException {
if(x<18) {
MyException e = new MyException();
throw e;
}
else {
System.out.print("You Can Vote");
}
}
}
class Test {
public static void main(String[] a)
{
Vote v = new Vote();
Scanner s=new Scanner(System.in);
System.out.print("Enter Age: ");
int age = s.nextInt();
try {
v.input(age);
}
catch(MyException e) {
e.show();
}
}
}
Expected Output
//Output 1 : Enter Age: 19 You Can Vote // Output 2 : Enter Age: 14 You Can't Vote
Explanation of the Program
- Java provides hundreds of built-in exceptions, but sometimes your business logic requires something specific (like an
InvalidAgeExceptionorInsufficientFundsException). - To create a custom exception, you simply create a normal class and force it to inherit from
Exception. - You then use the
throwkeyword to physically trigger the exception when your business rules are violated (e.g., age < 18). - Because it inherits from
Exception(which is a checked exception), any method that throws it must declare it in its signature using thethrowskeyword.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)