Question: JAVA 2 All the exceptions that we have dealt with so far are all created by the JVM. Some other exceptions we will encounter soon,
JAVA 2
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.
New Exception Example
/*****************************************************************************
New Exception Class
For Lab
*****************************************************************************/
class MyNewException extends Exception {
// ================== Properties =========================
private String errMsg = "My New Error Message ======>";
// ==================== Methods ==========================
public String toString() { return errMsg; }
public void display() {
System.out.println("MyNewException Error Message: "+ errMsg);
}
}//end class
Complete Tester class Example:
/*****************************************************************************
Test Exception Class
For Lab
*****************************************************************************/
class TestNewException {
public void throwingMethod(int x) throws MyNewException{
if (x==0)
throw new MyNewException();
else
System.out.println(" X = "+x);
}
public static void main(String args[]) {
TestNewException te1 = new TestNewException();
try {
te1.throwingMethod(3); //this code will not throw an exception
te1.throwingMethod(0); //this code WILL throw an exception
}
catch(MyNewException e) {
System.out.println(e); //calling toString() method
e.display(); //calling display method
}
} //end main()
} //end class
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
