What is the difference between checked and unchecked exceptions?

22

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?

  • asked by anonymous 27.03.2014 / 03:44

    3 answers

    19

    Unchecked exceptions:

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

    Checked Exceptions:

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

    Organization in classes :

    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:

    Conclusion:

    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!

        
    27.03.2014 / 04:49
    7

    What is an exception?

      

    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 raised      

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

    >

    When were exceptions created?

      

    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

    When Differed Checked and Unchecked?

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

    Exception mechanism in Java?

      

    According to the book .

         

    The Java exception mechanism is based on C++ , but is designed to be more   object-oriented paradigm.   All exceptions are class objects 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 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   in Java 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.

    How should I use it now?

    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.

    29.03.2014 / 21:50
    5

    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 .

        
    27.03.2014 / 15:52