When a method throws an exception, Java requires that it be caught. Some exceptions require action on the programmer’s part and others simply need to be reported to the user. The Java class that we will develop in this article is concerned with the latter type of exception. Instead of rewriting code every time you need to catch an exception, you can create a class to do most of the work for you.
The constructor’s first argument (line 21) is an object of the Exception class so this class or any of its subclasses may be passed in. It won’t matter whether you pass in an IOException, an SQLException or any other subtype. The second argument is a Component that will act as the parent window for our dialogue box. Again we have chosen Component because it is the parent object of the various window subclasses.
On line 22 the constructor invokes a method, “doDialogue”, to extract the error message and display it using a JOptionPane. The interesting part of this method is the call to a function to insert a newline character but let’s first look at the output.
Output
Compiling and running the application results in the following output (Image 1):
followed by (Image 2):
This is the same message formatted in two different ways. Now that we’ve seen the output let’s have a look at how it’s done.