Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it a "bad idea" to throw your own exceptions?

Why is it a "bad idea" to throw your own exceptions?

found here

like image 726
acheo Avatar asked Feb 06 '10 23:02

acheo


People also ask

Why is it bad to throw exceptions?

throw is not simply an alternative way of returning a value from a function (similar to return ). Doing so will be slow and will confuse most C++ programmers who are rightly used to seeing exceptions used only for error handling. Similarly, throw is not a good way of getting out of a loop.

Is it bad practice to throw exceptions?

It is good practice to throw exceptions if you have appropriate exception handling. Don't blindly throw exceptions until the application crashes. In your option 1 example, an ArgumentException is more appropriate. Your option 2 is more appropriate for data validations.

Should you always throw an exception?

You should only use exceptions for exceptional situations. An exceptional situation is an unexpected situation that is out of the ordinary. A situation is not exceptional just because it's less common than other situations. In a non-exceptional situation you should use return values instead of exceptions.

Why would you need to write your own exception?

Custom exceptions provide you the flexibility to add attributes and methods that are not part of a standard Java exception. These can store additional information, like an application-specific error code, or provide utility methods that can be used to handle or present the exception to a user.


3 Answers

In general, it is perfectly fine to throw your own exceptions. Perhaps what you meant to ask was "When is it not necessarily a good idea to throw my own exception?"

One case is when you should be throwing a standard exception. For example, if your method takes a file name and is supposed to return a file, you should probably throw your platform's standard FileNotFoundException rather than throw PeanutPowersFileNotFoundException. If you really want to throw your own exception, you should probably have it extend the standard FileNotFoundException.

Update: Bloch explains this in Item 60 of Effective Java

like image 74
Peter Recore Avatar answered Sep 30 '22 18:09

Peter Recore


It's not. You should create and throw custom exceptions whenever you have an exceptional situation.

like image 38
Samuel Neff Avatar answered Sep 30 '22 18:09

Samuel Neff


It isn't provided they are derived from whatever the standard base exception type is (std::exception in c++, or Exception in python, etc...)

If they _aren't_derived from the normal base type, then other people may not catch them when they are expecting to catch all exceptions - which would be a bad thing.

like image 41
James Avatar answered Sep 30 '22 20:09

James