Hello! I have some doubts about exceptions, which are:
What is the main difference between checked and unchecked exceptions?
In what situations should I use each one?
What are good usage practices?
Hello! I have some doubts about exceptions, which are:
What is the main difference between checked and unchecked exceptions?
In what situations should I use each one?
What are good usage practices?
These are bugs.
Are subclasses of RuntimeException
and are usually implemented using IllegalArgumentException
, NullPointerException
or IllegalStateException
.
A method is not required to establish a policy for the unchecked exceptions thrown by its execution (and almost never ever do).
Unexpected exception example:
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);
}
Invalid conditions in areas beyond the immediate control of the program (problems of invalid user input, database, network failures, missing files).
Are subclasses of Exception
.
A method is required to establish a policy for all checked exceptions thrown by its implementation (or pass the exception checked above on the stack, or manipulate it in some way). >
Some examples of exceptions checked:
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);
}
It's a bit confusing, but note that RuntimeException
(not checked) is by itself a subclass of Exception
(checked).
Since in some cases a picture is worth a thousand words, note:
The ideal is to always treat all exceptions to your program (checked or not) and avoid using throws Exception
.
Any questions please ask in the comments. I hope I have helped!
According to the famous book . We consider hardware-detectable errors, such as an incorrect disk reading and unconventional situations, such as an end-of-file exception. We further extend the concept of exception to include or conditions detectable by software.
Therefore, we define exception (
exception
) as an unusual event, caused by error or not, that hardware, software or both are detectable and may require special handling.The 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 thread and is called an exception handler . An exception is raised ( raised ) when its associated event occurs. In some language based on
C
, exceptions are said to be thrown instead of raisedNote:
>C++
was the first language toC
style to include exception handling. The word throw was used in place of raised , because the default library ofC
already included a function called raise .
Programming languages: Principles and Practice, 2nd edition, by Kenneth C. Louden (A noteworthy book on programming languages) has a note "The PL / I language pioneered Exception Management in the 1960s, in CLU language in the 70's. However it was only in the 80's and beginning in the 90's that this issue was largely resolved.
If you have a question about these language you can view their history here .
If you want to know more about the language CLU
( link )
Ref: link
Java
made the first differentiation of checked and Unchecked as we see here and here
According to the book .
The
Java
exception mechanism is based onC++
, but is designed to be more object-oriented paradigm. All exceptions are class objects descending from the Throwable class. TheJava
system includes two predefined exceptions that are subclasses of Throwable: Error and Exception. The Error classes and their descendants are error referrals that are thrown by Java run-time. These exceptions are never thrown by user programs, and should never be dealt with there. There are two Exception traces: RuntimeException and IOException. In most cases RuntimeException is thrown when a user program causes some error. User programs can define their own classes of exceptions. The convention inJava
language is that user-defined exceptions are subclasses of Exception.Exceptions from the Error and RuntimeException classes are called unchecked exception . All other exceptions are called checked exceptions .
ThereistheOracletutorialonJavaexceptionhandling here .
In short for checked exceptions you are required to catch the exception and treat it even if you just print it out.
I believe you should use unchecked exceptions, as indicated by Robert C Martin's Clean Code book.
Checked exceptions can sometimes be useful if you are creating a critical library: you must capture them. But in the overall application development, dependency costs outweigh the benefits.
Then use mostly unchecked exceptions unless you're doing something that has to be checked at any cost.
Briefly, Checked
exceptions are those in which you are required to treat it, either with a try-catch block or even with a throws (relaunching it to another location). On the other hand, when you have exceptions of type Unchecked
it is not mandatory to treat it, you can only treat 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 error can be handled, you use Checked Exceptions
, otherwise use Unchecked Exceptions
.