valdrus (valdrus) wrote in java_faq,
valdrus
valdrus
java_faq

difference between checked and Unchecked Exceptions in Java

Unchecked exceptions are any class of exception that extends the RuntimeException class at some point in its inheritance hierarchy. This includes the most common exceptions. An ArithmeticException occurs when a program tries to divide by zero. A NullPointerException occurs when you try and access an instance data member or method of a reference variable that does not yet reference an object.

Unchecked exceptions can occur anywhere in a program and in a typical program can be very numerous. Therefore, the cost of checking these exceptions can be greater than the benefit of handling them. Thus, Java compilers do not require that you declare or catch unchecked exceptions in your program code. Unchecked exceptions may be handled as explained for checked exceptions in the following section.

All Exceptions that extend the RuntimeException class are unchecked exceptions.

Checked exceptions are exceptions that do not extend the RuntimeException class. Checked exceptions must be handled by the programmer to avoid a compile-time error. One example of a checked exception is the IOException that may occur when the readLine method is called on a BufferedReader object. Read more about the readLine method in the section on console input in the Java I/O page. All other exceptions you may have experienced were examples of unchecked exceptions.

There are two ways to handle checked exceptions. You may declare the exception using a throws clause or you may catch the exception. To declare an exception, you add the keyword throws followed by the class name of the exception to the method header. See example below. Any method that calls a method that throws a checked exception must also handle the checked exception in one of these two ways.
  • Post a new comment

    Error

    Anonymous comments are disabled in this journal

    default userpic

    Your IP address will be recorded 

  • 0 comments