How to create a Custom Exception in Java
Points To Remember
- All the custom Exceptions must implement the Exception class or any of its subclass.
- There are four types of Constructors that you can use while defining your Custom Exception.
Ex 1 : Basic Custom Exception
In this case we will just created a Custom Exception where we define a Custom Exception and throw it with a message. This message is visible in the stacktrace.class CustomException extends Exception { public CustomException(String message) { super(message); } } public class Test { public static void main(String args[]) { try { throw new CustomException("Throwing Custom Exception"); } catch (CustomException e) { e.printStackTrace(); } try { throw new CustomException(" ThrowingAnother Custom Exception"); } catch (CustomException e) { e.printStackTrace(); } } }The output of the above example is
CustomException: Throwing Custom Exception
at Test.main(Test.java:12)
CustomException: ThrowingAnother Custom Exception
at Test.main(Test.java:17)
at Test.main(Test.java:12)
CustomException: ThrowingAnother Custom Exception
at Test.main(Test.java:17)
Ex 2 : Custom Exception with same Message
Suppose we have a Custom Exception and we know that it will occur only because of a particular reason that we can throw the Exception without the Constructor Parameter like the following.class CustomException extends Exception { public CustomException() { super("Custom Exception has Occured"); } } public class Test { public static void main(String args[]) { try { throw new CustomException(); } catch (CustomException e) { e.printStackTrace(); } try { throw new CustomException(); } catch (CustomException e) { e.printStackTrace(); } } }
CustomException: Custom Exception has Occured
at Test.main(Test.java:12)
CustomException: Custom Exception has Occured
at Test.main(Test.java:17)
at Test.main(Test.java:12)
CustomException: Custom Exception has Occured
at Test.main(Test.java:17)
This is a small example how you can define your own Custom Exceptions in java
No comments: