Easy to Learn Java: Programming Articles, Examples and Tips

Start with Java in a few days with Java Lessons or Lectures

Home

Code Examples

Java Tools

More Java Tools!

Java Forum

All Java Tips

Books

Submit News
Search the site here...
Search...
 
Search the JavaFAQ.nu
1000 Java Tips ebook

1000 Java Tips - Click here for the high resolution copy!1000 Java Tips - Click here for the high resolution copy!

Java Screensaver, take it here

Free "1000 Java Tips" eBook is here! It is huge collection of big and small Java programming articles and tips. Please take your copy here.

Take your copy of free "Java Technology Screensaver"!.

Easy Learn Java: Programming Articles, Examples and Tips - Page 384


Previous 1060 Stories (530 Pages, 2 Per Page) Next

Making Exceptions Unchecked

Go to all tips in Story by Dr. Kabutz

The Java Specialists' Newsletter [Issue 033] - Making Exceptions Unchecked

Author: Dr. Heinz M. Kabutz

JDK version:

Category: Exceptions

You can subscribe from our home page: http://www.javaspecialists.co.za (which also hosts all previous issues, available free of charge Smile

Welcome to the 33rd issue of "The Java(tm) Specialists' Newsletter", which some cynics say should be renamed to "The Java(tm) Hackers' Newsletter". Yes, ok, that would probably be a more appropriate name considering some of our articles, but I just find that examining some of the weird behaviour in Java helps me to understand the language better.

Thanks to all of you who responded to my last survey where I asked you to send me email if you could *not* read my newsletter. You remind me of my good friend at university who won ALL the class medals for Computer Science. I once managed to beat him in a subject (parallel computing) where I got 90+% and he got 65%. He had thought he should answer 2 out of 4 questions, whereas he should have answered 3 out of 4 questions! The problem was that he did not read the question Wink

Meanwhile, my mailbox is quickly filling up with requests for information about the new Design Patterns course. If you have 10 or more programmers in your company that would like to attend such a course, please send me an email and I will see if I can pop around for a visit.

How do you go from being an OO beginner to an OO guru? Simple answer: Experience! What if you can't wait 10 years to get that experience? Simple answer: Design Patterns! How can you learn Design Patterns in a relaxed setting from someone who has used them in the real world? Simple answer: Ask me about my new course "Design Patterns - The Timeless Way of Coding".

Why Checked Exceptions Cause Bugs

How often have you seen code such as this?

  // ...
  try {
    // ... some code that could throw IOException or RemoteException
  } catch(Exception ex) {} // ignore

Or even worse, how about the following (from a real program whose author shall remain anonymous):

  Connection con;
  try {
    // ... make a connection
  } catch(Throwable t) {
    con = null;
  }

You can imagine what happened. At some point, the piece of code that needed to make the connection tried to load a class that was not in the classpath, with a resulting NoClassDefFoundError. The program stopped working without informing us of what had gone wrong. After a while I noticed that the class could not have been included in the classpath and was horrified to find the above code.

Why is it that so many novice Java developers write code that catches Exception and then keeps quiet about it? Is it because the compiler forces us to catch them - and most beginners then don't know how to handle them correctly? I personally like checked exceptions because they tell me what things could go wrong in my environment, although not always very clearly. For example, java.io.IOException has 47 subclasses in JDK 1.3.1, so if a method throws IOException you really don't know what actually went wrong.


Sometimes I want to catch several checked exceptions and then do something about them as a group. The problem with catching Exception is that you then also catch the unchecked exceptions, i.e. derivatives of java.lang.RuntimeException, such as NullPointerException. I like to call the unchecked exceptions programmer bug exceptions and in general you would not want to swallow those exceptions. In that case I normally do the following:

  // ...
  try {
    // ... some code that could throw IOException or RemoteException
  } catch(RuntimeException ex) {
    // programmer bug - rethrow
    throw ex;
  } catch(Exception ex) {
    // handle all the exceptions correctly
  }

Incorrect handling of exceptions is the cause of most of the bugs I have seen in novice Java programmers' code. Seeing that most Java programmers are novices due to the age of the language, we could say that, even though I like them, checked exceptions could perhaps have been a mistake. C++ doesn't have them, neither does C# and also not Python. (In case you think I'm a great visionary for thinking that they might be a mistake, I got that idea from someone else Wink

Wrapping Checked Exceptions in Unchecked Exceptions

So how do you convert a checked exception into an unchecked exception? Here we have a code sample of how one could write an Object Adapter that would convert a checked exception into a RuntimeException. (If you don't know the difference between an object and a class adapter, and what the applicability and the consequences of each are, you should seriously consider coming to my design patterns course - see beginning of newsletter for more information.)

One of the challenges of adapting exceptions is that you want to capture the exact place where the error occurred in the program, rather than the place where the checked exception was caught. The following would therefore not be the right way to do it, as you would have an incorrect line number to blame for the fault:

  // incorrect way of adapting a checked exception
  try {
    // ... some code that could throw IOException or RemoteException
  } catch(Exception ex) {
    throw new RuntimeException(ex.toString());
  }

After some experiments, I found that the ExceptionConverter shown below works fairly well.

/**
The ExceptionConverter changes a checked exception into an
unchecked exception.
*/
public class ExceptionConverter extends RuntimeException {
  /** we keep a handle to the wrapped exception */
  private final Exception ex;
  public ExceptionConverter(Exception ex) {
    this.ex = ex;
  }
  /** and allow the user of ExceptionConverter to get a handle to it. */
  public Exception getException() {
    return ex;
  }
  /** We print the message of the checked exception */
  public String getMessage() {
    return ex.getMessage();
  }
  /** and make sure we also produce a localized version */
  public String getLocalizedMessage() {
    return ex.getLocalizedMessage();
  }
  /** The toString() is changed to be prefixed with ExceptionConverter */
  public String toString() {
    return "ExceptionConverter: " + ex;
  }
  /** we have to override this as well */
  public void printStackTrace() {
    printStackTrace(System.err);
  }
  /** here we prefix, with s.print(), not s.println(), the stack
    trace with "ExceptionConverter:" */
  public void printStackTrace(java.io.PrintStream s) {
    synchronized (s) {
      s.print("ExceptionConverter: ");
      ex.printStackTrace(s);
    }
  }
  /** Again, we prefix the stack trace with "ExceptionConverter:" */
  public void printStackTrace(java.io.PrintWriter s) {
    synchronized (s) {
      s.print("ExceptionConverter: ");
      ex.printStackTrace(s);
    }
  }
  /** requests to fill in the stack trace we will have to ignore
  (I think)  We can't throw an exception here, as this method
  is called by the constructor of Throwable */
  public Throwable fillInStackTrace() {
    return this;
  }
}

We can try this out by throwing some exceptions around:

import java.io.IOException;
public class ExceptionConverterTest {
  private static void f() throws IOException {
    throw new IOException("File broken");
  }
  private static void g() {
    try {
      f();
    } catch(IOException ex) {
      System.out.println("Printing out plain ol' IOException:");
      System.out.println("---");
      ex.printStackTrace();
      System.out.println("---");
      throw new ExceptionConverter(ex);
    }
  }
  public static void main(String args[]) {
    try {
      g();
    } catch(RuntimeException ex) {
      System.out.println("Printing out RuntimeException:");
      System.out.println("---");
      ex.printStackTrace();
      System.out.println("---");
      System.out.println("That's it!");
    }
  }
}

The resulting output is:

Printing out plain ol' IOException:
---
java.io.IOException: File broken
        at ExceptionConverterTest.f(ExceptionConverterTest.java:5)
        at ExceptionConverterTest.g(ExceptionConverterTest.java:9)
        at ExceptionConverterTest.main(ExceptionConverterTest.java:20)
---
Printing out RuntimeException:
---
ExceptionConverter: java.io.IOException: File broken
        at ExceptionConverterTest.f(ExceptionConverterTest.java:5)
        at ExceptionConverterTest.g(ExceptionConverterTest.java:9)
        at ExceptionConverterTest.main(ExceptionConverterTest.java:20)
---
That's it!

As you can see, the line numbers for the two exceptions are the same, pointing us to the exact source of our troubles, without forcing us to use checked exceptions.

Is it a good idea to adapt checked exceptions into unchecked ones? In general I would say "no". However, there are some cases where you are overriding a method which does not throw a checked exception that you need to throw and in those cases it can sometimes be useful. How often have I morphed exceptions? Not often.

I'm looking forward to your comments on this newsletter.

Cheersio

Heinz


ERRATA

In my last newsletter I made a silly mistake - I forgot to set instance back to null. The make() method of the CleverLicenseManager class should have been:

  public static CleverLicenseManager make() {
    synchronized(CleverLicenseManager.class) {
      try {
        new CleverLicenseManager();
      } catch(Exception ex) {} // ignore
      try {
        while (instance == null) {
          System.gc();
          CleverLicenseManager.class.wait(100);
        }
        return instance;
      } catch(InterruptedException ex) {
        return null;
      } finally {
        instance = null;
      }
    }
  }

Copyright 2000-2004 Maximum Solutions, South Africa

Reprint Rights. Copyright subsists in all the material included in this email, but you may freely share the entire email with anyone you feel may be interested, and you may reprint excerpts both online and offline provided that you acknowledge the source as follows: This material from The Java(tm) Specialists' Newsletter by Maximum Solutions (South Africa). Please contact Maximum Solutions for more information.

Java and Sun are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries. Maximum Solutions is independent of Sun Microsystems, Inc.

10932 bytes more | comments? | Printer Friendly Page  Send to a Friend | Score: 0
Posted by jalex on Saturday, July 16, 2005 (00:00:00) (3080 reads)

Question: What is SWT? And what is useful for?

Go to all tips in Swing, AWT

Question: What is SWT? And what is useful for?

Answer: SWT is a widget toolkit for Java designed to provide efficient, portable access to the user-interface facilities of the operating systems on which it is implemented.

The most succinct description of the Standard Widget Toolkit component is this:

The SWT component is designed to provide efficient, portable access to the user-interface facilities of the operating systems on which it is implemented.

The SWT component implementors take each of the terms in this statement to have a very specific meaning:

"efficient"

implies that SWT must be as thin a layer on top of the operating system facilities as possible. So, for example, SWT avoids the use of a separate peer layer as is found in the Sun AWT class library, thereby gaining increased speed and space efficiency at the cost of some amount of implementation flexibility. SWT also attempts to avoid "sugar coating" the limitations of the underlying operating system, since doing this always implies significant overhead in addition to introducing the potential for subtle failures and incompatabilities; this is the "sometimes you have to let the o/s win" rule. An example of the kind of problem that SWT would not attempt to hide is the existence of limitations on cross-threaded access to widgets.
The only exceptions to the rule are cases where a particular operating system is missing features that are required for it to be a candidate Eclipse platform. If some small set of specific, clearly defined "workarounds" can be made to enable Eclipse to run on this target, then they will be implemented. For example, the lack of a ToolBar type widget on Motif was addressed by providing an "emulated" version on that window system, since ToolBars are fundamental to the Eclipse look and feel.


"portable"
implies both that it must be possible to create applications (Eclipse, in particular) which will run on all of the supported operating systems, and that SWT itself must be simple to port to new operating systems.

The former case is supported by providing a common programming interface. By coding to this API, applications can be created that run everywhere where SWT will run. It is important to note that, because SWT uses the native (i.e. operating system provided) widgets, the look and feel of applications built with SWT will vary on each operating system so that they match the expectations of users of that operating system.

The later case, the porting of SWT itself, is supported by ensuring that all but the lowest-level, direct interface to the operating system is written in Java. In SWT there truly is "nothing interesting in the C natives", which makes the initial porting (and subsequent debugging) of SWT considerably easier since it can largely be done using the facilities of Eclipse, including the built in remote debugging. In addition, the coding style of SWT is such that it is easy for programmers that are familiar with a particular operating system to understand and implement the code.

A side-effect of the SWT implementation strategy is that it is relatively simple to create operating system specific extensions to SWT to support particularly important features. An example of this would be ActiveX on Windows, which Eclipse uses (protected by appropriate platform checks) to support embedded ActiveX controls and do*****ents. It was felt that to be competitive on that platform, support for ActiveX was a requirement, even though it was not available elsewhere. Because SWT is "close" to the platform, this was not a difficult task.
"access to the user-interface facilities of the operating system"
Although this has already been stated, it is worth reiterating that the widgets that the SWT component provides are those that are provided by the operating systems on which SWT runs. The intent is to allow access to these native widgets (and the other operating system user-interface facilities), not to "roll our own" new widget system. As such, although the SWT component implementors try very hard to make it possible for consumers of SWT to be able to ignore which operating system they are running on, developers need to understand that applications can potentially behave differently to match the operating system behavior. For example, programatically giving focus to a "radio" button on Windows will cause it to be selected. Period. Since it would be exceedingly difficult (and is counter to the Windows user-interface look and feel) to prevent this behavior, the Windows version of SWT generates events as if the user had "clicked" the radio button when it is given focus. This means that well-written applications can ignore the differences, but also means that smart developers will test SWT applications on every platform which they are to be delivered on.
Custom Widgets

If that was all there was to this story, then everything would be clear cut. However, in addition to the work described above, the SWT component is responsible for one additional aspect of Eclipse: the implementation of the custom widgets which provide the specific look and feel (i.e. the "branding") of Eclipse. This is a complex task, since it requires a delicate balance between the particular vision of the user-interface designers, and the desire for the widgets to have appearance and behavior that is consistant with the user-interface guidelines of the operating system.

It is important to note that, if Eclipse were to be built entirely from custom widgets and used no native widgets, then the SWT component implementors would consider their work to be a failure. The intent is to provide a small set of carefully considered custom widgets to give Eclipse its distinguishing features in a way that is still strongly oriented towards the look and feel of the platform. For example, when the user modifies the appearance of their desktop using platform provided mechanisms (setting default window background colors, border widths, "skinning", etc.) the custom widgets should reflect these changes whenever (a) the changes can be detected and (b) they do not specifically contradict the brand appearance.

Currently, all custom widgets are coded in terms of existing SWT widget and graphics APIs. They are portable and use underlying SWT mechanisms to ensure that they have correct appearance. Although this already works quite well, one of the research areas for the SWT component is to further improve the ability to match the platform appearance, for example in the presence of "programatic skinning" as provided by window systems such as GTK+. Embedded Systems Another exciting aspect of SWT is that it is also being used as part of the underlying implementation for several embedded systems efforts because of its small size and focus on efficiency. The most notable of these, currently at least, is in the AWT implementation provided as part of the VisualAge/MicroEdition class libraries, where SWT effectively becomes the peer layer for AWT. Further effort is ongoing to improve SWT's utility in this area.

And finally, one last aside: The above discussion blurs and sometimes ignores the distinction between operating systems and window systems. We do understand the difference, but wanted to avoid making things even more verbose than they already were.

All this info, a lot of code snippets and more info on SWT can be found here..


6389 bytes more | comments? | Printer Friendly Page  Send to a Friend | Score: 0
Posted by Anonymous on Thursday, July 14, 2005 (00:00:00) (3034 reads)

Previous 1060 Stories (530 Pages, 2 Per Page) Next

530| 529| 528| 527| 526| 525| 524| 523| 522| 521| 520| 519| 518| 517| 516| 515| 514| 513| 512| 511| 510| 509| 508| 507| 506| 505| 504| 503| 502| 501| 500| 499| 498| 497| 496| 495| 494| 493| 492| 491| 490| 489| 488| 487| 486| 485| 484| 483| 482| 481| 480| 479| 478| 477| 476| 475| 474| 473| 472| 471| 470| 469| 468| 467| 466| 465| 464| 463| 462| 461| 460| 459| 458| 457| 456| 455| 454| 453| 452| 451| 450| 449| 448| 447| 446| 445| 444| 443| 442| 441| 440| 439| 438| 437| 436| 435| 434| 433| 432| 431| 430| 429| 428| 427| 426| 425| 424| 423| 422| 421| 420| 419| 418| 417| 416| 415| 414| 413| 412| 411| 410| 409| 408| 407| 406| 405| 404| 403| 402| 401| 400| 399| 398| 397| 396| 395| 394| 393| 392| 391| 390| 389| 388| 387| 386| 385|
384
| 383| 382| 381| 380| 379| 378| 377| 376| 375| 374| 373| 372| 371| 370| 369| 368| 367| 366| 365| 364| 363| 362| 361| 360| 359| 358| 357| 356| 355| 354| 353| 352| 351| 350| 349| 348| 347| 346| 345| 344| 343| 342| 341| 340| 339| 338| 337| 336| 335| 334| 333| 332| 331| 330| 329| 328| 327| 326| 325| 324| 323| 322| 321| 320| 319| 318| 317| 316| 315| 314| 313| 312| 311| 310| 309| 308| 307| 306| 305| 304| 303| 302| 301| 300| 299| 298| 297| 296| 295| 294| 293| 292| 291| 290| 289| 288| 287| 286| 285| 284| 283| 282| 281| 280| 279| 278| 277| 276| 275| 274| 273| 272| 271| 270| 269| 268| 267| 266| 265| 264| 263| 262| 261| 260| 259| 258| 257| 256| 255| 254| 253| 252| 251| 250| 249| 248| 247| 246| 245| 244| 243| 242| 241| 240| 239| 238| 237| 236| 235| 234| 233| 232| 231| 230| 229| 228| 227| 226| 225| 224| 223| 222| 221| 220| 219| 218| 217| 216| 215| 214| 213| 212| 211| 210| 209| 208| 207| 206| 205| 204| 203| 202| 201| 200| 199| 198| 197| 196| 195| 194| 193| 192| 191| 190| 189| 188| 187| 186| 185| 184| 183| 182| 181| 180| 179| 178| 177| 176| 175| 174| 173| 172| 171| 170| 169| 168| 167| 166| 165| 164| 163| 162| 161| 160| 159| 158| 157| 156| 155| 154| 153| 152| 151| 150| 149| 148| 147| 146| 145| 144| 143| 142| 141| 140| 139| 138| 137| 136| 135| 134| 133| 132| 131| 130| 129| 128| 127| 126| 125| 124| 123| 122| 121| 120| 119| 118| 117| 116| 115| 114| 113| 112| 111| 110| 109| 108| 107| 106| 105| 104| 103| 102| 101| 100| 99| 98| 97| 96| 95| 94| 93| 92| 91| 90| 89| 88| 87| 86| 85| 84| 83| 82| 81| 80| 79| 78| 77| 76| 75| 74| 73| 72| 71| 70| 69| 68| 67| 66| 65| 64| 63| 62| 61| 60| 59| 58| 57| 56| 55| 54| 53| 52| 51| 50| 49| 48| 47| 46| 45| 44| 43| 42| 41| 40| 39| 38| 37| 36| 35| 34| 33| 32| 31| 30| 29| 28| 27| 26| 25| 24| 23| 22| 21| 20| 19| 18| 17| 16| 15| 14| 13| 12| 11| 10| 9| 8| 7| 6| 5| 4| 3| 2| 1|


Home Code Examples Java Forum All Java Tips Books Submit News, Code... Search... Offshore Software Tech Doodling

RSS feed Java FAQ RSS feed Java FAQ News     

    RSS feed Java Forums RSS feed Java Forums

All logos and trademarks in this site are property of their respective owner. The comments are property of their posters, all the rest 1999-2006 by Java FAQs Daily Tips.

Interactive software released under GNU GPL, Code Credits, Privacy Policy