Question
Java 2 Building your own Exceptions Why Build your own Exceptions? All the exceptions that we have dealt with so far are all created by
Java 2
Building your own Exceptions
Why Build your own Exceptions?
All the exceptions that we have dealt with so far are all created by the JVM. Some other exceptions we will encounter soon, like IOException and SQLException are created by classes that are part of the Java API, so I consider them also Java created exception.
We may want to create our own Exceptions for Business reasons. For example, Java has no Exceptions that deal with Financial issues, but we may want to create some of these for a Financial Application that we are building.
If we want to build our own Exception, we will have to build the exception class, and then throw this exception when we encounter a situation that calls for this error. The User of our code that throws the exception will have to put their calls in a try/catch block.
Building your own Exception class
Create a new class call it the name you want to call your exception. (i.e. MyNewException). This class must inherit from the Exception class.
Add a property to the class, which includes the error message for this new exception. You do not need to add a constructor, because you will get the no-args constructor from Java. You will want to have a way to display or output the error message. So I usually add a toString() method and/or a display() method. Both can be useful.
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started