Query regarding custom exception class | Core Java Forum
Vikrant Posted on 19/07/2021

Hi Yogesh,

When I create my own exception class and extends that class using Exception which is parent of all exception. Later you have used constructor to call 

parent class method eg. super (message) in constructor. Instead of constructor can I not use any method to call the parent class method? 

If yes then how ? please explain?


Yogesh Chawla Replied on 19/07/2021

You can also create toString function to present the same message like below which earlier we were getting it by calling parent Exception class constructor.


class InvalidAgeException extends Exception {

	String message;

	public InvalidAgeException(String message) {
		this.message = message;

	public String toString() {
		return ("MyException Occurred: " + message);

public class LetsTestOurOwnExceptionClass {

	public static void main(String[] args) {

		try {
		} catch (InvalidAgeException e) {


	static void validate(int age) throws InvalidAgeException {

		if (age >= 18) {
			System.out.println("User can vote");
		} else {
			throw new InvalidAgeException("User can not vote");