What should exceptions be used for?

What should exceptions be used for?

Exceptions should be used for situation where a certain method or function could not execute normally. For example, when it encounters broken input or when a resource (e.g. a file) is unavailable. Use exceptions to signal the caller that you faced an error which you are unwilling or unable to handle.

When should you always use exception handling?

Use exceptions to check error conditions that might occur at run time even if your code is correct, for example, “file not found” or “out of memory.” Exceptions can handle these conditions, even if the recovery just outputs a message to a log and ends the program.

Can a error be turned into an exception?

Errors can sometimes be turned into exceptions so that they can be handled within the code. Errors can usually be avoided with simple checks and if simple checks won’t suffice errors can also turn into exceptions, so that the application can handle the situation gracefully.

What should exceptions be thrown for invalid or?

Exceptions are to handle exceptional situation, not bugs, and not user’s (i.e. API consumer) shortfalls. Throwing exceptions for invalid arguments is rude, unless you write a library. Assertions don’t need to be tested, while throw assertions do, and test against ArgumentNullException looks ridiculous (try it).

Which is more important an error or an exception?

An error in the code creating multiple incorrect billing charges is usually more important than an error which fails to display a specific details page, even if the details page error happens more often. Ultimately, you want your application to run into as little as possible but when it does run into exceptions, you want to know about it.

How to handle errors and exceptions in large scale?

Throwing and catching exceptions is a great way to let the application recover by itself and prevent it from running into an error state. If you know which type of exceptions might be thrown, it is better to be explicit within the catch block as each different type of exception will mean the code has unforeseeably stopped for a different reason.