23

While reading about exception, I will always come across checked exceptions and unchecked exceptions, So wanted to know how to distinguish that which is what?

Edit: I want to know if i create any exception class then how can i create as a checked or as an unchecked?

and what is the significance of each?

GuruKulki
  • 25,776
  • 50
  • 140
  • 201

6 Answers6

27

All Throwables except subclasses of java.lang.RuntimeException or java.lang.Error are checked. Properly, in Java, "exceptions" are subclasses of java.lang.Exception, "errors" are subclasses of java.lang.Error and java.lang.Throwable is not usually subclassed directly.

Programs are not supposed to create their own Error subclasses (though the documentation is rather ambiguous on that) so generally you always create Exceptions, using a RuntimeException if you don't want it to be checked.

To know at run-time if you have a checked exception you could use:

if(throwable instanceof Exception && !(throwable instanceof RuntimeException)) {
    // this is a checked Exception
    }

A checked exception is one which must be either handled in a catch clause, or declared as being thrown in the method signature; the compiler enforces this. Generally, one uses checked exceptions for exceptions which should be handled by the calling code, while unchecked exceptions are for conditions which are the result of a programming error and should be fixed by correcting the code.

That said there is much debate in the Java community about the efficacy of using checked exceptions vs. unchecked exceptions everywhere - a subject way to deep to discuss in this answer.

EDIT 2012-10-23: In response to comments (which are quite valid), to clarify, the following would be what is required to determine if a captured Throwable is a checked Throwable as opposed to a checked Exception:

if(obj instanceof Throwable && !(obj instanceof RuntimeException) && !(obj instanceof Error)) {
    // this is a checked Throwable - i.e. Throwable, but not RuntimeException or Error
    }

If the object in question is known to be an instance of Throwable (e.g. it was caught), only the second part of the above 'if' is needed (e.g. testing for Throwable is redundant).

Lawrence Dol
  • 63,018
  • 25
  • 139
  • 189
  • 1
    This misses exceptions which inherit from `Throwable` but not from `Exception`, which are checked. Generally you have: An unchecked 'exception' t will satisfy: `t instanceof Error || t instanceof Exception` Everything else which is `instanceof Throwable` is checked. An error is a type of Exception in the general sense. – BeeOnRope Oct 22 '12 at 21:16
  • @Bee: In one sense that's quite correct; but, `Error`s are ***Errors***, not ***Exceptions***, and Java makes the distinction in naming (`Error` handling is another case where theory fails in practice, but, I thought, a related yet separate discussion). That is, `Error`s are also checked, but in Java nomenclature they are errors, not exceptions; However both errors and exceptions are `Throwable`s. According to Java, an `Error` is a `Throwable` but not an `Exception` (more generally in English, `Error`s are "exceptions", but they are not "Exceptions"). – Lawrence Dol Oct 23 '12 at 18:10
  • 1
    Exactly. That said, I'd assume a method which decided whether a throwable was a checked or not would return true for all checked exceptions, not just checked Exceptions. That is, it would take the little e sense of the word. I can't see a valid use case for excluding things which extend `Throwable` but not `Exception` or `Error`. What do you call those anyway? – BeeOnRope Oct 23 '12 at 19:05
  • @Bee: I don't call them anything; I've never encountered someone using a direct subclass of `Throwable`. BTW I have updated my answer to assuage your concern. – Lawrence Dol Oct 24 '12 at 04:40
  • Looks good. Often the check itself for `instanceof Throwable` can be itself omitted because if you caught something, it must be a `Throwable`. Similarly for `Exception` if you caught `Exception` (or a subclass), etc. – BeeOnRope Oct 24 '12 at 06:50
  • 1
    @Bee: Yes, that's what I meant by my last paragraph. – Lawrence Dol Oct 24 '12 at 16:47
6

See the Java Language Spec, chapter 11:

The unchecked exceptions classes are the class RuntimeException and its subclasses, and the class Error and its subclasses. All other exception classes are checked exception classes. The Java API defines a number of exception classes, both checked and unchecked. Additional exception classes, both checked and unchecked, may be declared by programmers.

You could check this via instanceof at runtime, though I don't really see where this would be useful.

As to the second part of your question:

  • checked exception represent expected error conditions, which can occur during normal program execution and therefore always have to be handled programatically (which the compiler enforces)

  • unchecked exception represent unexpected error conditions and signify an abnormal state of your program, due to invalid input, bugs or runtime restrictions (eg memory); the compiler won't force the programmer to handle these, ie you only have to care for them if you know of their occurrence

Christoph
  • 164,997
  • 36
  • 182
  • 240
  • @Christoph: and of course there's a whole school of programming that consider that "an expected error condition" is not really an error and that seen that a lot of languages do perfectly fine without even the *concept* of checked exception their existence is debatable. Joshua Bloch, Effective Java, *"Prefer state testing method over exception"*. And then of course there's the school of programming that hates GOTOs and considered using checked exceptions for flow control to be spaghetti-like GOTO programming. I'm not siding with one camp or another, just stating the current state of affair :) – SyntaxT3rr0r Mar 10 '10 at 22:07
3

Java checked vs unchecked exception

  • Error is internal VM error and usually you can not manage it.
  • Exception - you are able to catch and handle it

Checked vs Unchecked

  • checked exception is checked by the compiler and as a programmer you have to handle it using try-catch-finally, throws
  • unchecked exception is not checked by the compiler but you optionally can manage it explicitly

IntelliJ IDEA's Type Hierarchy tool is useful when you want to find more

yoAlex5
  • 29,217
  • 8
  • 193
  • 205
2

If the exception class is a subclass of RuntimeException, it's not checked and does not have to be declared for functions or caught, etc. Error exceptions also do not have to be declared/caught. Is that what you're asking?

roottraveller
  • 7,942
  • 7
  • 60
  • 65
Pointy
  • 405,095
  • 59
  • 585
  • 614
0

Quite sure this will have been asked and answered before, but for the sake of it, it is covered quite nicely here: http://www.javapractices.com/topic/TopicAction.do?Id=129.

Strictly speaking, unchecked exceptions will always extend RuntimeException whereas checked exceptions do not. The mentioned link explains when to use either.

As their name indicates, callers are obliged to deal with checked exceptions, typically handling them (try/catch) or passing them further up the stack. Unchecked exceptions are usually deemed to be caused by elements outside of the caller's control.

Derek Mortimer
  • 1,061
  • 1
  • 8
  • 11
-2
package practice;

import java.io.IOException;

class Practice
{
    public static void main(String args[])
    {
        Exception n=new NullPointerException();
        if(n instanceof RuntimeException)
        {
            System.out.println("this is a runtime(unchecked) exception");
        }
        else
        {
            System.out.println("this is not a compiletime(checked) exception");
        }

    }

}