Summary
Throwing (or raising) an exception halts execution of your program at that point, and execution proceeds in the most immediately available
catchblock (exception handler).A bug is a programming mistake that should be fixed before the program is released. An exception, however, is the result of a predictable but unpreventable problem that arises during runtime (for example, running out of disk space).
When a program encounters a problem that it cannot solve or work around, it may throw an exception to halt execution and allow the exception handler to fix or work around the problem.
All exceptions used in C# derive from
System.Exception, and all exceptions in your program should derive fromSystem.Exception.You can throw an exception yourself using the
throwkeyword.It is good programming practice to enclose code that has a high risk of throwing an exception within a
tryblock and to provide an exception handler (acatchblock) and perhaps afinallyblock.The
catchblock follows thetryblock and contains the code used to handle the exception.If an exception was not raised within a
tryblock, or there is nocatchblock, the stack is unwound until acatchblock is found. If nocatchblock is ever found, the built-in exception handler is invoked, which terminates your program with an error message.You can create dedicated
catchstatements to catch specific types of exceptions taking advantage of the inheritance hierarchy of exceptions.Any action that must be taken whether or not ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access