What is the difference between checked and unchecked exceptions?

Hello! I have some doubts about exceptions, which are:

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

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

  3. What are the good use practices?

Author: AndersonBS, 2014-03-27

3 answers

Unchecked Exceptions):

  • Represent program defects (bugs).

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

  • A method is not required to establish a policy for unchecked exceptions thrown by its execution (and almost always never do so).

Example of exception not check:

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);
}

 

Checked Exceptions):

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

  • Are subclasses of Exception.

  • A method is required to establish a policy for all checked exceptions thrown by your implementation (or pass the exception checked higher up in the stack, or manipulate it in some way).

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 :

Is a bit confusing, but note that RuntimeException (unchecked) is itself a subclass of Exception (checked).

Since in some cases a photo is worth a thousand words, Note:

insert the description of the image here

Conclusion:

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

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

 21
Author: AndersonBS, 2020-06-11 14:45:34

What is exception?

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

Therefore, we define exception (exception) as an unusual event, 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 the exception handler. An exception is raised ( raised) when its associated event occurs. In some C - based language, exceptions are said to be thrown(thrown) instead of raised (raised )

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

When were exceptions created?

Programming Languages: Principles and Practice, 2nd edition, by Kenneth C. Louden (a notable book on programming languages) has a annotation " the PL/I Language pioneered exception Management in the 1960s, and advanced significantly in the CLU language in the 1970s. In any case it was only in the 80s and beginning in the 90s that this issue was largely resolved.

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

If you want to know more about the 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 differentiated?

The Java Did the first differentiation of checked and Unchecked as we see here and here

Exception mechanism in Java?

According to the book .

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

Exceptions of the Error and RuntimeException classes are called unchecked exception. All other exceptions are called checked exceptions .

insert the description of the image here

There Is Oracle's tutorial on Java Exception Handling here .

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

Currently How Should I use?

I believe that unverified exceptions should be used, as indicated by Robert C Martin's book - Clean Code.

As checked exceptions can sometimes be useful if you're building a critical library: you need to capture them. But in general application development, the costs of dependency outweigh the advantages.

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


 8
Author: Leonardo Otto, 2017-05-23 12:37:27

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 (relaunching the same to another location). On the other hand, when you have exceptions of the type Unchecked it is not mandatory to treat it, you can treat only if you want, if you feel that it is necessary for the proper functioning of your application. Checked exceptions are used for recoverable errors while Unchecked exceptions are used for errors unrecoverable. It means to say that when you know that your error can be dealt with, you use Checked Exceptions, otherwise you use Unchecked Exceptions.

 5
Author: guiandmag, 2014-03-27 14:52:20