Search code examples
javaexceptionchecked-exceptions

create checked exception class in java


I am puzzled about creating checked exception class in java.

Many article says custom exception can be created by

class MyException extends Exception
{
  //constructor defined
}

Since RuntimeException is also inherited from Exception class.

Is it not possible to create a class that will cover only Checked Exceptions ?

Or I need to specify list of checked exceptions

class MyException extends IOException
    {
      //constructor defined
    }

In above code, there can be a scenario where i would miss certain checked exceptions.


Solution

  • This:

    class MyException extends IOException,FileNotFoundException
    

    is simply not possible in Java. A class can only extend one other class.

    The point is:

    • when you extend Exception you are creating a checked exception.
    • when you extend RuntimeException you are creating an unchecked exception

    That is all there is to this. And yes, you are correct, it is a bit awkward that RuntimeException extends Exception but is not a checked exception. But this fact is basically "baked" into the Java language, and there is nothing you can do about that (besides knowing and accepting).

    And as you updated your question - when you do:

    public class MyException extends IOException
    

    then you create a checked exception that is also an IOException! So to be precise: when you extend Exception, or any of the subclasses ob Exception (except RuntimeException) you are creating a checked exception!