Summary
Throwing (or raising) an exception halts execution of your program at that point, and execution proceeds in the most immediately available
catch
block (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
throw
keyword.It is good programming practice to enclose code that has a high risk of throwing an exception within a
try
block and to provide an exception handler (acatch
block) and perhaps afinally
block.The
catch
block follows thetry
block and contains the code used to handle the exception.If an exception was not raised within a
try
block, or there is nocatch
block, the stack is unwound until acatch
block is found. If nocatch
block is ever found, the built-in exception handler is invoked, which terminates your program with an error message.You can create dedicated
catch
statements to catch specific types of exceptions taking advantage of the inheritance hierarchy of exceptions.Any action that must be taken whether or not ...
Get Learning C# 3.0 now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.