32. Custom Exception Program - prabhatrocks07/Core-Java-Programming GitHub Wiki

public class CustomExceptionTest {

public static void main(String[] args) {
	System.out.println("Enter the age: ");
	Scanner sc = new Scanner(System.in);
	int age = sc.nextInt();
	sc.close();
	
	try {
		validateAge(age);
	} catch (MyException e) {
		e.printStackTrace();
	} finally {
		System.out.println("Execution completed");
	}
}

private static void validateAge(int age) throws MyException {
	if(age >= 18) {
		System.out.println("You are eligible for vote");
	} else {
		throw new MyException("Not eligible for vote");
	}
}

}

class MyException extends Exception {

private static final long serialVersionUID = -6992941860563344457L;
String message;

public MyException(String message) {
	super(message);
	this.message = message;
}

@Override
public String toString() {
	return "MyException [message=" + message + "]";
}	
}