Created
January 16, 2019 12:59
-
-
Save theArjun/28164795a6ed89ba7cbf21d52bcfb38e to your computer and use it in GitHub Desktop.
Creating your own Exception in Java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Create your own Exception. | |
| class MyException extends Exception { // Inherits the partially unchecked exception class Exception. | |
| MyException(String msg) { // Parameterized constructor for MyException. | |
| super(msg); // Calls the constructor of Exception class; super class. | |
| } | |
| } | |
| class ExceptionDemo { | |
| static void isValid(int age) throws MyException { // Denotes this code may contain Exception; declaring exception here. | |
| if(age < 18){ | |
| throw new MyException("Age is less than 18."); | |
| }else{ | |
| System.out.println("Cool, age is greater than 18."); | |
| } | |
| } | |
| public static void main(String[] args){ | |
| try{ | |
| isValid(17); // Age is 17; which is less than 18 and should exception. | |
| }catch(MyException error){ | |
| error.printStackTrace(); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment