However, Java's built-in exceptions handle most common errors, yet you may want to create your own custom exception types to handle situations specific to your applications. The main reasons for creating custom exceptions are:
1. Business logic exceptions – Exceptions that are specific to the business logic and workflow. Such exceptions help the application users or the developers understand what the exact problem is.
2. To catch and provide specific treatment to a subset of existing Java exceptions.
Creating a user defined exception in java is fairly easy. You just need to define a subclass of Exception
(which is a subclass of Throwable
). Your subclass don't need to actually implement anything.
The Exception
class does not define any methods of its own. It inherits those methods provided by Throwable
. Thus, all exceptions, including those created by you, have the methods defined by Throwable
available to them.
Let's create a user defined exception step by step:
1. Create a new class whose name should end with Exception like ClassNameException. This is a convention to differentiate an exception class from regular ones.
2. Extend the generic Exception
class
3. Create a constructor with a String parameter which is the detail message of the exception. In this constructor, simply call the super constructor and pass the message.
Take a look at the following code example to understand custom exception creation.
class MyException extends Exception { public MyException(String message) { super(message); } } public class Test { public static void main(String args[]) throws MyException { File file = new File("path"); try { FileInputStream fis = new FileInputStream(file); } catch (FileNotFoundException ex) { throw new MyException("this is custom exception"); } } } Output: Exception in thread "main" MyException: this is custom exception at Test.main(Test.java:17)
Hope you have enjoyed reading How to create user defined or custom exception class in Java? Please do write us if you have any suggestion/comment or come across any error on this page. Thank you for reading!
Share this page on WhatsApp