User-defined exception
- Eclipse: Oxygen
- Java: 1.8
User defined exception is manually defined by the users as suggested by the name. For example, while developing a simple HTML form we want to throw an exception when the password length is less than 8 than such exceptions are used.
Syntax
1 2 3 |
class UserDefinedException extends Exception{ } |
In the following program, we have created a user-defined exception by extending Exception class. We provide the exception information through try and catch block.
Through catch block, we provide the bracket e and hold the information that this is an exception of Exception, FileNotFoundException, UserDefinedException which is customized created.
Then keyword “throw” is used to create a new Exception (Exception, FileNotFoundException, UserDefinedException) and throw it to the catch block. “throw” keyword always written inside the method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
class UserDefinedException extends Exception{ } public class App { public static void main(String[] args) { try { someMethod(); } catch (FileNotFoundException e) { System.out.println("catch block of main method(FileNotFoundException)"); } catch (UserDefinedException e){ e.printStackTrace(); }catch (Exception e) { System.out.println("catch block of main method (Exception)"); } } public static void someMethod() throws Exception,FileNotFoundException, UserDefinedException { int x = 3; switch (x) { case 1: throw new FileNotFoundException(); case 2: throw new Exception(); default: throw new UserDefinedException(); } } } |
Always remember when you create your own exception keep the following point in your mind:
- All exception should be a child of Throwable.
- If you want to write a checked exception that is automatically enforced by the Handle or declare rule, you must extend the Exception class.
Contributed by Poonam Tomar