Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to demonstrate custom exception class .

Java Code Example — Exception Handling Programs

ADVERTISEMENT

Java Program to demonstrate custom exception class .

Objective

Write a Java program to create and throw a Custom Exception class.

Algorithm / Approach

  1. Create a class MyException that extends Exception.
  2. Inside it, create a custom method show() that prints an error message ("You Can't Vote").
  3. Create a Vote class with a method input(int x) throws MyException.
  4. Inside input(), if the age is less than 18, manually throw new MyException();.
  5. In main, prompt for an age, wrap the call to input() in a try-catch block, and catch MyException.
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 InvalidAgeException or InsufficientFundsException).
  • To create a custom exception, you simply create a normal class and force it to inherit from Exception.
  • You then use the throw keyword to physically trigger the exception when your business rules are violated (e.g., age &lt; 18).
  • Because it inherits from Exception (which is a checked exception), any method that throws it must declare it in its signature using the throws keyword.

Complexity

Time Complexity O(1)
Space Complexity O(1)
ADVERTISEMENT