Thursday, June 4, 2015

The differences between checked exception and unchecked exception In Java

If your java program runs into exception, how should you do? You can catch and handle it, or catch and throw it up, or just do not catch it. The way handle exception is depended on the type of exception.

There are two types of java exception: checked exception and unchecked exception.

Unchecked exceptions:

  1.        represent defects in the program (bugs) - often invalid arguments passed to a non-private method.
  2.        are subclasses of RuntimeException, and are usually implemented using IllegalArgumentException, NullPointerException, or IllegalStateException
  3.        a method is not obliged to establish a policy for the unchecked exceptions thrown by its implementation (and they almost always do not do so)


Checked exceptions:

  1.        represent invalid conditions in areas outside the immediate control of the program (invalid user input, database problems, network outages, absent files)
  2.        a method is obliged to establish a policy for all checked exceptions thrown by its implementation (either pass the checked exception further up the stack, or handle it somehow)

Tips for Java Programmer


If your program runs into RuntimeException, that always indicates that you need to fix the bug. To quote from The Java Programming Language, by Gosling, Arnold, and Holmes: "Unchecked runtime exceptions represent conditions that, generally speaking, reflect errors in your program's logic and cannot be reasonably recovered from at run time."

So if you catch the RuntimeException, please fix the bug ASAP. Perhaps you want to know your programs throw RuntimeException by monitoring tools, you can try the EasyHA.

New Feature of EasyHA Monitoring Tool


The new version of EasyHA will analyze log file of your java program, and detect the unique RuntimeException. And the head of Ops team can check number of bugs by figures and diagrams.


No comments:

Post a Comment