How to define custom exception in java

Sometimes we need custom exceptions for our application like while developing banking application we need custom exception for withdraw to check the available amount in user account.

To define custom exception you just need to inherits base Exception class and override toString() method.

Define Custom Exception

Here we’re defining a custom exception class which throws custom exception if age is greater than 50.

CustomException.java

package com.startwithjava;
public class CustomException extends Exception {
private int age;
public CustomException(int age){
this.age = age;
}

public String toString(){
return "Age should not be greater than " +age;
}

}

ExceptionTest.java


package com.startwithjava;

import java.util.Scanner;

public class ExceptionTest {

public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
Scanner sc= new Scanner(System.in);
System.out.println("Please enter you age!");
int age = sc.nextInt();

if(age >50)
throw new CustomException(age);
else
System.out.println("Your age is :"+age);

}

}

Leave a Reply