-1

In the custom exception class we call constructor of super class(Exception class).Why don't we call directly Exception class constructor instead of custom class constructor ? Please find the example below

class InvalidAgeException extends Exception {
    InvalidAgeException(String s) {
        super(s);
    }
}

class TestCustomException1 {

    static void validate(int age) throws InvalidAgeException {
        if (age < 18) {
            throw new InvalidAgeException("not valid");
        }
        else {
            System.out.println("welcome to vote");
        }
    }

    public static void main(String args[]){  
        try {  
            validate(13);  
        }
        catch (Exception m) {
            System.out.println("Exception occured: " + m);
        }
        System.out.println("rest of the code...");
    }
}

In the above example we can use throw new Exception("not valid"); Then what is the use of custom exception class here ?

MC Emperor
  • 22,334
  • 15
  • 80
  • 130
user2155454
  • 95
  • 3
  • 12
  • Using `throw new Exception("not valid");` - how would you know when reading the logs that it's meant to be `InvalidAgeException`? – achAmháin Jul 01 '19 at 12:14

1 Answers1

0

Because it lets the calling code have more control about which exceptions it needs to care about. In this case main only catches the base Exception class, but what if in the future someone adds a method that only cares about invalid ages, but not other types of exceptions?

0x5453
  • 12,753
  • 1
  • 32
  • 61