create checked exception class in java

1.4k views Asked by At

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.

2

There are 2 answers

0
GhostCat On BEST ANSWER

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!

0
davidxxx On

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

Covering an exception ?
I think that you misunderstand the exception concept. Any exception that you will create doesn't cover all exception as the exception root class is Exception and not your custom exception class.

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

You want to represent an exception that may wrap any checked exception ?
So provide a field in your constructor class to associate your exception with any checked exception :

public class MyCheckedException extends Exception
{
   public MyCheckedException(Exception causeException){
     super(causeException);
   }
}