What is the difference between checked (checked) and unchecked (unchecked) exceptions?

Asked

Viewed 8,791 times

23

Hello! I have some questions about exceptions, which are they:

  1. What is the main difference between checked and unchecked exceptions?

  2. In which situations should I use each of them?

  3. What are good usage practices?

3 answers

21


Exceptions not checked (unchecked):

  • Represent defects in the program (bugs).

  • Are subclasses of RuntimeException and are typically implemented using IllegalArgumentException, NullPointerException or IllegalStateException.

  • A method is not required to establish a policy for unverified exceptions released by its execution (and almost always do).

Example of exception not checked:

int num1 = 10;
int num2 = 0;
int res = 0;

res = num1 / num2; // ArithmeticException: / by zero;

Possible solution:

int num1 = 10;
int num2 = 0;
int res = 0;

try {
    res = num1 / num2;
} catch (ArithmeticException ex) {
    Logger.getLogger(Teste.class.getName()).log(Level.SEVERE, null, ex);
}

 

Exceptions checked (checked):

  • Represent invalid conditions in areas outside the immediate control of the program (invalid user input issues, database, network failures, missing files).

  • Are subclasses of Exception.

  • A method is required to establish a policy for all checked exceptions released by its implementation (or pass the exception checked further up the stack, or manipulate it somehow).

Some examples of checked exceptions:

FileInputStream FIS = null;
FIS = new FileInputStream("D:/arquivo.txt"); // erro: unreported exception FileNotFoundException;

int x;
while ((x = FIS.read()) != 0) { // erro: unreported exception IOException;
}

Possible solution:

FileInputStream FIS = null;
try {
    FIS = new FileInputStream("D:/arquivo.txt");
} catch (FileNotFoundException ex) {
    Logger.getLogger(Teste.class.getName()).log(Level.SEVERE, null, ex);
}
        
int x;
try {
    while ((x = FIS.read()) != 0) {
    }
} catch (IOException ex) {
    Logger.getLogger(Teste.class.getName()).log(Level.SEVERE, null, ex);
}

 

Class organization:

It’s a little confusing, but note that RuntimeException (not checked) is by itself a subclass of Exception (check).

Since in some cases a photo is worth more than a thousand words, note:

inserir a descrição da imagem aqui

Completion:

The ideal is to always treat all the exceptions of your program (checked or not) and avoid the use of throws Exception.

Any questions ask in the comments. I hope I’ve helped!

  • In the picture, the class Error should be unchecked.

8

What is an exception?

According to the famous book. We consider hardware-detectable errors as incorrect disk reading and unconventional situations, such as an end of file as exceptions. We further extend the concept of exception to include or conditions detectable by software.

Therefore, we set exception (exception) as an unusual event, whether caused by error or not, that is detectable hardware, software or both and that may require special treatment.

Special processing that may be required when an exception is detected is called Exception Handling. This processing is done by a unit of code or by a segment and is called Exception Handler. An exception is raised(Raised) when your associated event occurs. In some language based on C, exceptions are said as moves(thrown) in place of raised (Raised)

Note: C++ was the first language to style C to include exception treatment. The word throw was used instead of Raised, because the standard library of C already included a function call raise.

When exceptions were made?

Programming Languages: Principles and Practice, 2nd Edition, by Kenneth C. Louden (A remarkable book on programming languages) has an annotation "The PL/I language pioneered Exception Management in the 1960s, and advanced significantly in the CLU language in the 1970s. Anyway it was only in the 80s and early 90s that this issue was largely resolved.

If you have a question about these languages you can see their history here.

If you want to know more about language CLU (http://publications.csail.mit.edu/lcs/pubs/pdf/MIT-LCS-TR-561.pdf)

Ref:https://stackoverflow.com/a/1458013/1792268

When was Checked and Unchecked?

The Java made the first differentiation of checked and unchecked as we see here and here

Exception mechanism in Java?

According to the book.

The mechanism of exception of Java is based on the C++, but is designed to be more directed towards object-oriented paradigm. All exceptions are descending class objects of the Throwable class. The system Java includes two predefined exceptions that are subclasses of Throwable:Error and Exception. The Error classes and their descendants refer to errors that are released by the Java run-time. These exceptions are never released by users' programs, and should never be dealt with there. There are two descendants of Exception: Runtimeexception and Ioexception. In most cases Runtimeexception is released when a user program causes some mistake. User programs can define their own exception classes. The convention in the language Java is that exceptions defined by the user are subclasses of Exception.

Exceptions of the Error and Runtimeexception classes are called unchecked Exception. All other exceptions are called checked exceptions.

inserir a descrição da imagem aqui

There is Oracle’s tutorial on the Java exception handling here.

Briefly for checked exceptions you are required to capture the exception and treat it, even if you just print that an error has occurred.

Currently how I should use?

I believe that we should use unverified exceptions, as indicated by Robert C Martin’s book - Clean Code.

Verified exceptions can sometimes be useful if you are creating a critical library: you need to capture them. But in general application development, dependency costs outweigh the advantages.

So use mostly unverified exceptions unless you are doing something that has to be verified at any cost.


5

Briefly the exceptions Checked are those in which you are required to treat it, either with a Try-catch block or even with a throws (re-releasing the same to another location). On the other hand, when you have exceptions like Unchecked it is not mandatory to treat it, you can treat only if you want, if you feel it is necessary for the proper functioning of your application. Checked exceptions are used for recoverable errors while Unchecked exceptions are used for unrecoverable errors. It means that when you know that your mistake can be dealt with, you use Checked Exceptions, otherwise use Unchecked Exceptions.

  • Excellent. Simple explanation, but no less forceful than the previous ones. And to force a method to be used with an exception of the checked type, one must use the statement throws and the name of the class or subclass from Exception - being the mother of all exception treatment classes of the checked type - immediately after the closing parenthesis in the method declaration.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.