How can I add condition in custom exceptions in java?

While reading values from the user in the constructor or any method you can validate those values using if condition.


In the following Java example we are defining two custom exception classes verifying name and age.

import java.util.Scanner;
class NotProperAgeException extends Throwable{
   NotProperAgeException(String msg){
class NotProperNameException extends Throwable{
   NotProperNameException(String msg){
public class CustomException{
   private String name;
   private int age;
   public static boolean containsAlphabet(String name) {
      for (int i = 0; i < name.length(); i++) {
         char ch = name.charAt(i);
         if (!(ch >= 'a' && ch <= 'z')) {
            return false;
      return true;
   public CustomException(String name, int age){
      try {
         if (age<0||age>125) {
            String msg = "Improper age (not between 0 to 125)";
            NotProperAgeException exAge = new NotProperAgeException(msg);
            throw exAge;
         }else if(!containsAlphabet(name)&&name!=null) {
            String msg = "Improper name (Should contain only characters between a to z (all small))";
            NotProperNameException exName = new NotProperNameException(msg);
            throw exName;
      }catch(NotProperAgeException e) {
      }catch(NotProperNameException e) {
      } = name;
      this.age = age;
   public void display(){
      System.out.println("Name of the Student: " );
      System.out.println("Age of the Student: "+this.age );
   public static void main(String args[]) {
      Scanner sc= new Scanner(;
      System.out.println("Enter the name of the person: ");
      String name =;
      System.out.println("Enter the age of the person: ");
      int age = sc.nextInt();
      CustomException obj = new CustomException(name, age);


Enter the name of the person:
Enter the age of the person:
Name of the Student: Krishna
Age of the Student: 136
july_set3.NotProperAgeException: Improper age (not between 0 to 125)
at july_set3.CustomException.<init>(
at july_set3.CustomException.main(

Enter the name of the person:
Enter the age of the person:
Name of the Student: !23Krishna
july_set3.NotProperNameException: Improper name (Should contain only characters between a to z (all small))
Age of the Student: 24
at july_set3.CustomException<init>(
at july_set3.CustomException.main(

Updated on: 06-Aug-2019


Kickstart Your Career

Get certified by completing the course

Get Started