Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between throwing Exception and throwing a specific Exception such as NullPointerException

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.

like image 440
L1ghtk3ira Avatar asked Dec 18 '22 15:12

L1ghtk3ira


2 Answers

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.
}
like image 128
Karolis Kajenas Avatar answered May 12 '23 01:05

Karolis Kajenas


There are at least two reasons why you would want to throw a specific kind of exception:

  1. If a program fails with an exception, you will have more information with which to determine what went wrong. Compare seeing Exception with FileNotFoundException. The latter clearly gives you more information.
  2. In some cases, the code will want to catch certain kinds of exceptions. For example, when working with serial ports, you might want to catch and handle a TimeoutException differently from a NullReferenceException.
like image 43
Matthew Watson Avatar answered May 12 '23 03:05

Matthew Watson