Explanation
This Java program demonstrates the fundamental concept of creating a user-defined exception and subsequently handling that exception when it occurs during program execution.
The core idea is to define a condition (in this case, checking if a person's age is less than 18) that the standard Java exceptions don't naturally cover, and then signal this specific error using our own custom exception class, MyException.
- Defining the Custom Exception (
MyException): A new class namedMyExceptionis created thatextends Exception. This inheritance is crucial because it marksMyExceptionas a checked exception (meaning the compiler forces you to handle it). The constructor simply calls the parentExceptionclass's constructor usingsuper(msg)to store the error message provided when the exception is thrown. - Main Logic (
OwnExceptionEg): In themainmethod, a variableageis initialized to15. - The Check and Throw: An
ifstatement checks ifage < 18. Since $15 < 18$ is true, the program executes the linethrow new MyException("Age must be 18 or above");. This immediately halts the normal flow of execution in thetryblock and searches for a matchingcatchblock. - Handling the Exception: The execution jumps to the
catch (MyException e)block. This block is specifically designed to catch instances of our custom exception. Inside the catch block,e.printStackTrace()is called. This method prints the complete stack trace of the exception to the console, showing exactly where the error occurred, including the custom message defined during the throw.