Download presentation
Presentation is loading. Please wait.
1
Programming in C# Lesson 5. Exceptions.
2
Defining “Exception” An exception is when a class member fails to complete the task it is supposed to perform as indicated by its name.
3
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
4
Handling Exceptions In C# exception can be handled with try-catch-finally construction
5
Handling Exceptions: Complete Example
6
Exceptions in .NET System.Exception is a base class for all exceptions in .NET
7
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)
8
Custom Exceptions To define a custom exception class it needs to be inherited from System.Exception
9
Mind the hierarchy! When catching an exception of a particular class all derived exceptions are caught too.
10
Order catch blocks from specific to general!
11
Throwing Exceptions Exceptions are thrown by using throw keyword.
12
How Exceptions Work?
13
Re-throwing Exceptions
14
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
15
try-finally block
16
using block
17
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)
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.