• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

Checked and Unchecked Exceptions

 
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Can anybody explain what is the difference between checked and unchecked Exceptions? Giving and example would benefit me.

Thanks in Advance...........
 
Ranch Hand
Posts: 81
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Checked Exceptions:
  • A checked exception is any subclass of Exception (or Exception itself), excluding class RuntimeException and its subclasses.
  • You should compulsorily handle the checked exceptions in your code, otherwise your code will not be compiled. i.e you should put the code which may cause checked exception in try block. "checked" means they will be checked at compiletime itself.
  • There are two ways to handle checked exceptions. You may declare the exception using a throws clause or you may use the try..catch block.
  • The most perfect example of Checked Exceptions is IOException which should be handled in your code Compulsorily or else your Code will throw a Compilation Error.


  • Unchecked Exceptions :
  • Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses also are unchecked.
  • Unchecked runtime exceptions represent conditions that, generally speaking, reflect errors in your program's logic and cannot be reasonably recovered from at run time.
  • With an unchecked exception, however, compiler doesn't force client programmers either to catch the exception or declare it in a throws clause.
  • The most Common examples are ArrayIndexOutOfBoundException, NUllPointerException ,ClassCastException

  •  
    Ranch Hand
    Posts: 69
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    When you compile your code the compiler Checks for Exceptions that may be thrown and that are not properly handled.

    However it does not check for every possible exception that exists, just some of the most basic common ones (after all you could create your own kind of exception and it wouldn't be checked).

    So a checked exception is an exception that the compiler looks for in your code that may be thrown or otherwise handled incorrectly.

    I'll do an example you can run on your machine, hold on a mo!
     
    Robert Elbourn
    Ranch Hand
    Posts: 69
    • Likes 1
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    package randomtest;

    public class UncheckedTester {

    /**
    * @param args
    */
    public static void main(String[] args) {
    // TODO Auto-generated method stub

    int dontDivideMeByZero = 5;
    int result = dontDivideMeByZero/0;

    }

    }

    run the above code in a file called UncheckedTester in an appropriate directory etc.... and you will see that it compiles, but throws an exception at runtime (hence runtime exception)

    run the below code and you will find that it wont compile because there is an IOException that MAY be thrown, this is checked and an error is reported before it can be compiled, if you remove the '//removed' tags you will find out that it compiles and runs and probably works without exception.

    package randomtest;

    import java.io.File;
    import java.io.FileWriter;

    public class CheckedTester {

    /**
    * @param args
    */
    public static void main(String[] args) {
    // TODO Auto-generated method stub

    File file = new File("WrittenFile.txt");
    //removedtry {
    FileWriter fileWriter = new FileWriter(file);

    fileWriter.write("This is what I am talkin'bout");
    removed//} catch (java.io.IOException ioe) {
    removed//System.out.println("Exception caught"+ioe);
    removed//}
    }

    }



    to explain further this was extracted from here
    http://elvis.rowan.edu/~hartley/Courses/OOPDA/Handouts/bj12.html


    There are two kinds of exception objects: checked and unchecked. Unchecked exceptions are subclasses of the RuntimeException class (either built in to Java or defined by the user). Checked exceptions are subclasses of the Exception class (that are not subclasses of RuntimeException). RuntimeException is a direct subclass of Exception.

    Exceptions built in to Java for null pointers, index values out of bounds, and class cast errors at runtime are of the unchecked kind. Exceptions dealing with file IO (and many others) are of the checked kind. If you define your own exception classes, the guidelines are as follows.

    Checked exceptions (extends Exception): for circumstances beyond the program's control, like file does not exist, disk full, etc. These are unpredictable and could occur at any time. The program should continue and try to work around the problem, such as telling the user the file does not exist and prompting for a file name again.
    Unchecked exceptions (extends RuntimeException): for circumstances the program could prevent or avoid with more or better coding, like null pointer, index out of bounds, illegal class cast. These should not occur and should be fixed if they do. The program should not continue


    further reading here: http://java.sun.com/docs/books/jls/second_edition/html/exceptions.doc.html
     
    Greenhorn
    Posts: 3
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Anyway, for the purposes of anyone learning for the SCJP, it would be nice if there was a list of all the checked exceptions thrown in the packages used for the SCJP. As it is, lots of questions deal with whether it is a "Compiler Error" or a "Runtime Exception", meaning you have to know whether the exception is checked or unchecked. Say, concerning threads for example, InterruptedException is checked but IllegalMonitorState is not etc. etc.

    If we had a list of all checked ones to memorize (and not just always IO, which is always the one used as an examples), it would be easier to prepare for that sort of questions. If anyone has ever found such a list, I would be really grateful if it could be posted here (of course I know that there can always be new checked or unchecked exceptions and that every single case can be looked up in the API docs, but I do not want to browse the docs for all classes that are on the SCJP if someone else has already done that.)
     
    Greenhorn
    Posts: 19
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Hi Saravanan,

    Regarding the one of the statement mentioned regarding Checked exception is where my doubt is

    --You should compulsorily handle the checked exceptions in your code, otherwise your code will not be compiled. i.e you should put the code which may cause checked exception in try block. "checked" means they will be checked at compiletime itself.

    I guess it should be reframed in this way

    ---Your code should handle (or) declare the checked exception.
     
    Don't get me started about those stupid light bulbs.
    reply
      Bookmark Topic Watch Topic
    • New Topic