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 code to create our first dialogue box is found on lines 55-69. Because the String class does not have an “insertAt” method, the error description is converted to a StringBuffer. The space character closest to the midpoint is found and a newline is inserted at that point. Basically the string is cut in half. Have a look at Image 1 above to see what it looks like.
This method is easy to understand and easy to code, hence the method name. Calling it “quickAndDirty” doesn’t quite do justice to this approach; it might well be suitable in other circumstances. Here though, any string of a few hundred characters would create problems. Pretty soon we’d have a dialogue box that stretched across or beyond the screen width.
Second Method
The shortcomings of the first method spawned method number two. The pseudo code for this method could be briefly written as:
get first portion of the string get tail end while not end of string find next most proximate space in tail end create substring of text up to this point concatenate this new string with original portion add on a newline end while
A reasonable enough starting point but turning this into suitable code didn’t prove easy. Using almost twice as many lines of code as the “quickAndDirty” method, we end up with the dialogue box shown as Image 2.
This method does exactly what is wanted, but the code doesn’t have the clarity of the first. This is important not only for writing the code but for maintaining it. This code works –- but like the driver who refuses to ask for directions, we came the long way round. We grimly stayed behind the wheel and finally got there. There must be a better way.