I am wondering what is the difference between throwing just Exception
and throwing a specific Exception such as NullPointer Exception
.
To my current knowledge an Exception
should be able to catch any type of exception where as using a specific Exception expects that only that exception type can be thrown.
Example:
void test(String testString) throws Exception;
vs
void test(String testString) throws NullPointerException;
If this is correct than to me it makes sense to just always throw Exception and to never name a specific exception. Am I missing something important here? Does it at the very least effect performance at all? A lot of people are looking between throwing and catching exceptions but nobody asks this very basic question.
I do not see a benefit of throwing any exception except Exception
.
To start off, Exception
is a base type of every Exception
. Just like object
is for everything.
By throwing a specific Exception
you provide more information to the consumer of what has happened.
Imagine scenario where you get a plain Exception
without a message, consumer is lost. When for example framework throws a NullReferenceException
, then you are aware of a fact that one of your objects does not have a reference which it was trying to access.
This is how you can chain exceptions and make use of their types:
try
{
throw new NotImplementedException();
}
catch(NullReferenceException ex)
{
// Logic for NullReference exception if needed.
}
catch(NotImplementedException ex)
{
// This will be executed.
}
catch(Exception ex)
{
// Will catch every exception.
}
There are at least two reasons why you would want to throw a specific kind of exception:
Exception
with FileNotFoundException
. The latter clearly gives you more information.TimeoutException
differently from a NullReferenceException
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With