What other exception classes need when only an exception class can handle all types of exceptions?

In one of my interviews, the interviewer asked me a question about several blocks catch. Question: why do we need other child classes Exceptionto handle the exception, if only the parent class, i.e. Exception, can handle all other exceptions.

+4
source share
4 answers

There are various advantages to using self-written subclasses of Exception or RuntimeException:

  • You can add additional information (fields) to your exception, which you will pass to the log. This can be useful to more easily track errors or provide the user with additional information that he can provide to you if his application crashes.
  • You can more easily distinguish between the various causes of errors and therefore decide how to solve different error situations (for example, you could use the IllegalArgumentException if any argument you entered is incorrect so that you can prompt the user to enter a valid argument; on the other hand IOException shows that you couldn't read / write your data at all)
+2
source

I quote from a basic Oracle tutorial

" , . , , , - , , . , , . , , , , ".

. : http://docs.oracle.com/javase/tutorial/essential/exceptions/advantages.html

+1

We use exception subclasses such as

FileNotFoundException

so that we display the correct message.

If we used only the exception when the application throws an exception, we would not know what the exception is.

This is not very suitable for debugging. Using child classes also helps us better log exceptions.

0
source

Since we can handle different exceptions differently, for example:

catch (FileNotFoundException e){
    createNewFile();
} catch (IOException e){
    System.out.println("Everything is bad(");
}
0
source

Source: https://habr.com/ru/post/1620499/


All Articles