Handling Exception

Learn about handling exceptions in .NET using try-catch statements and provide customized error messages based on the exception type.

Some languages return error codes when something goes wrong. .NET uses richer exceptions designed only for failure reporting. When this happens, we say a runtime exception has been thrown.

Other systems might use return values that could have multiple uses. For example, if the return value is a positive number, it might represent the count of rows in a table, or if the return value is a negative number, it might mean some error code.

try-catch statement

When an exception is thrown, the thread is suspended, and if the calling code has defined a try-catch statement, it is given a chance to handle the exception. If the current method does not handle it, then its calling method is given a chance, and so on up the call stack.

The default behavior of the console app

The default behavior of a console app or a .NET Interactive notebook is to output a message about the exception, including a stack trace, and then stop running the code. The application is terminated. This is better than allowing the code to continue executing in a potentially corrupt state. Our code should only catch and handle exceptions that it understands and can properly fix.

Wrapping error-prone code in a try block

When we know a statement can cause an error, we should wrap that statement in a try block. For example, parsing from text to a number can cause an error. Any statements in the  ...