Programming in C# Lesson 5. Exceptions.
Defining “Exception” An exception is when a class member fails to complete the task it is supposed to perform as indicated by its name.
Exceptions Characteristics A classic implementation of the OOP exception model Deliver powerful mechanism for centralized handling of errors and unusual events Substitute procedure-oriented approach, in which each function returns error code Simplify code constructions and maintenance Allow the problematic situations to be processed at multiple levels
Handling Exceptions In C# exception can be handled with try-catch-finally construction
Handling Exceptions: Complete Example
Exceptions in .NET System.Exception is a base class for all exceptions in .NET
System.Exception class System.Exception provides information about the cause of the error or unusual situation via properties: Message – text description of the exception StackTrace – a snapshot of the stack at the moment the exception is thrown InnerException – an exception that caused the current exception (if any)
Custom Exceptions To define a custom exception class it needs to be inherited from System.Exception
Mind the hierarchy! When catching an exception of a particular class all derived exceptions are caught too.
Order catch blocks from specific to general!
Throwing Exceptions Exceptions are thrown by using throw keyword.
How Exceptions Work?
Re-throwing Exceptions
Choosing Exception Type When an invalid parameter is passed to a method: ArgumentException ArgumentNullException ArgumentOutOfRangeException When requested operation is not supported: NotSupportedException When a method is not implemented: NotImplementedException If no suitable standard exception class is available: Create your own exception class
try-finally block
using block
Best Practices Order catch blocks from more specific to more general Do not handle all exceptions disregarding their type When raising an exception always pass to the constructor good explanation messages and the inner exception (if any) Do not swallow exceptions Avoid throwing exceptions for normal situations (as they affect performance)