09.20. User Defined Exception

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

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.

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

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments