SlideShare a Scribd company logo
EXCEPTION GUIDELINES IN C#
AHMED HELMY | SENIOR SOFTWARE DEVELOPER
AGENDA
 Why Handle Errors?
 Error Codes Drawbacks
 Exceptions
 Introducing Exceptions
 Why Exceptions?
 Exception Types
 Understanding Exception Handling
 Guidelines
 Throw Exception Guidelines
 Exception Message Guidelines
 Catch Exception Guidelines
 Finally Block Guidelines
 Custom Exceptions Guidelines
 Expensive Exceptions
 Guards
 References & Discussion
WHY HANDLE ERRORS
 Prevent program crashes
 Chance to fix/retry
 Meaningful Message
 Graceful exit
 Opportunity to log error
“Good error handling code helps future maintainers understand what possible error conditions may occur and
how they can be handled.” – Jason Roberts
ERROR CODES DRAWBACKS
 Need to add if/switch statements every time method is called to check return codes
 Errors do not “bubble up” the call stack
 How do you deal with system errors?
 Out of memory
 Access violations
 How do you return an error from a constructor?
“Exceptions are the primary means of reporting errors in frameworks” - Microsoft
INTRODUCING EXCEPTIONS
 System.Exception
 Generated with the “throw” statement
 Different exception classes represent different errors
 Exception classes can contain additional error information
 Different exceptions can be handled differently
“An exception is any error condition or unexpected behavior that is encountered by an executing
program” – Microsoft Documentation
WHY EXCEPTIONS?
 Don’t need to know all error / success codes
 Don’t need if / switch statements everywhere method is called
 More readable
 No magic numbers / constants
 Exceptions can bubble up
 Catch exceptions higher up / in one place
 Handle system errors
 Generate exceptions from constructors
EXCEPTION TYPES
 Standard exceptions provided by the .NET Framework ( System )
 . NET Runtime (CLR) - . NET Framework
 OutOfMemory
 StackOverflow
 Exceptions provided by framework / library authors ( Third party )
 JsonSerialization
 Custom application exceptions ( Your code )
 RulesEngine
ILLUSTRATED C# 2012 [BOOK]
UNDERSTANDING EXCEPTION HANDLING
THROWING EXCEPTIONS
 Throw an Exception
 Understanding the Stack Trace
THROW EXCEPTION GUIDELINE
 DO specify the inner exception when wrapping exceptions.
 DO use an empty throw statement (throw;).
 Do not use exceptions for normal flow of control, if possible [Microsoft]
 E.g. input validation
 You expect input to invalid sometimes
 Not an exceptional situation
 Part of expected logic flow
 IsValid(xxx) method(s)
 DO NOT throw a System.Exception or System.ApplicationException.
 DO NOT have public members that return exceptions as the return value or an `out` parameter
 DO NOT throw exceptions from Exception Filter blocks as it returns false and it will be difficult to debug
EXCEPTION MESSAGE GUIDELINES
 Describes the reason for the exception
 Written for developer who going to handling the exception
 Should completely describe the error, and how to correct error (where possible / applicable)
 May sometimes be shown to end-user
 May sometimes be logged
 Correct grammar
 Correct punctuation
 Correct spelling
 End sentences with full stop
 Consider error message localization
 Should not include passwords, security, or sensitive data
CATCH EXCEPTION
 Catching Exceptions (Try, Catch, Finally)
 Catching Different Exception Types
 Re-throwing Exceptions
 Catching and Wrapping Exceptions
 Filtering Catch Blocks with Exception Filters
 Global Exception Handling
CATCH EXCEPTION GUIDELINES
 Catch only exceptions that you can handle
 Catch only little code that you need
 Catch exception only once per thread (DO NOT over-catch)
 Use Exception Logging Libraries
 CONSIDER terminating the process by calling `System.Environemt.FailFast` instead of throwing an exception if your code
encounters a situation where it is unsafe for further execution [Microsoft]
 DO NOT Handle Exceptions inside loops
 DO NOT hide (bury) exceptions you don’t fully handle
 Do not add a catch block that does nothing or just re-throws
 May just be to log the error
 Usually bad practice to ignore (swallow / trap) exceptions
 AVOID catching System.Exception or System.SystemException except in top-level exception handlers that perform final
cleanup operations before rethrowing the exception.
FINALLY BLOCK GUIDELINES
 AVOID explicitly throwing exceptions from inside the block
 Implicitly thrown exceptions resulting from calling methods that throw are acceptable
 Use for cleanup
 E.g. calling Dispose()
CUSTOM EXCEPTIONS
CUSTOM EXCEPTIONS GUIDELINES
 Naming convention: …Exception
 Implement standard 3 constructors
 Add additional properties where needed
 Never inherit from ApplicationException class
 Inherit from System.Exception (or your other custom exception)
 Keep the number of custom exception types a minimum
 Wrap inner exception if appropriate
 Interfacing with external API, DLL, service
 Use existing predefined .NET exception types where applicable, e.g.
 InvalidOperationException if property set/method call is not appropriate for current state
 ArgumentException (or derived) for invalid parameters
 Don’t use custom (or existing) exceptions for normal (non exceptional) logic flow
EXPENSIVE EXCEPTIONS
 CONSIDER performance overhead of throwing and handling exceptions
 Throw rates above 100 per second are likely to noticeably impact most application’s performance
 Huge StackTrace
GUARDS
 Design code to avoid exceptions
 Framework designers should design APIs so users can write code that does not throw exceptions
 Tester-Doer Pattern
 Try-Parse Pattern
 Instead of using `int Parse(string input)` use `bool TryParse(string input, out int result)`
 Check connection state before trying to close it `if(cn.State != ConnectionState.Closed) { cn.Close(); }`
 Consider returning null (or null object pattern) for extremely common errors
 Use Check and Guard clauses
REFERENCES & DISCUSSION
 Error Handling in C# with Exceptions by Jason Roberts
 Microsoft Documentation [Exceptions]
 Illustrated C# 2012 [Book]

More Related Content

Similar to Exception guidelines in c# (20)

PPTX
Exception Handlin g C#.pptx
R S Anu Prabha
 
PPTX
12. Exception Handling
Intro C# Book
 
PPT
Exceptions
DeepikaT13
 
PPT
Exceptions
motthu18
 
PPTX
Exceptions overview
Bharath K
 
PPTX
Chapter_4_WP_with_C#_Exception_Handling_student_1.0.pptx
ZachariahAbera
 
PPT
CLR Exception Handing And Memory Management
Shiny Zhu
 
PPT
12 Exceptions handling
maznabili
 
PPT
C# Exceptions Handling
sharqiyem
 
PPTX
Exception handling in .net
baabtra.com - No. 1 supplier of quality freshers
 
PDF
Design byexceptions
Asif Tasleem
 
PPTX
IakakkakjabbhjajjjjjajjajwsjException.pptx
KingDietherManay1
 
PPTX
6-Error Handling.pptx
amiralicomsats3
 
PDF
Internals of exceptions
Alexandra Hayere
 
PPTX
C Sharp Tutorial : C Sharp Exception
Courseing Online
 
PPTX
3.C#
Raghu nath
 
PPTX
Exception Handling in C#
Abid Kohistani
 
PPT
Exception
abhay singh
 
PPTX
IEEE ACM Studying the Relationship between Exception Handling Practices and P...
Gui Padua
 
PPTX
Azure Function App Exception Handling.pptx
Knoldus Inc.
 
Exception Handlin g C#.pptx
R S Anu Prabha
 
12. Exception Handling
Intro C# Book
 
Exceptions
DeepikaT13
 
Exceptions
motthu18
 
Exceptions overview
Bharath K
 
Chapter_4_WP_with_C#_Exception_Handling_student_1.0.pptx
ZachariahAbera
 
CLR Exception Handing And Memory Management
Shiny Zhu
 
12 Exceptions handling
maznabili
 
C# Exceptions Handling
sharqiyem
 
Design byexceptions
Asif Tasleem
 
IakakkakjabbhjajjjjjajjajwsjException.pptx
KingDietherManay1
 
6-Error Handling.pptx
amiralicomsats3
 
Internals of exceptions
Alexandra Hayere
 
C Sharp Tutorial : C Sharp Exception
Courseing Online
 
Exception Handling in C#
Abid Kohistani
 
Exception
abhay singh
 
IEEE ACM Studying the Relationship between Exception Handling Practices and P...
Gui Padua
 
Azure Function App Exception Handling.pptx
Knoldus Inc.
 

Recently uploaded (20)

PDF
Open Chain Q2 Steering Committee Meeting - 2025-06-25
Shane Coughlan
 
PPTX
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 
PDF
iTop VPN With Crack Lifetime Activation Key-CODE
utfefguu
 
PPTX
Help for Correlations in IBM SPSS Statistics.pptx
Version 1 Analytics
 
PDF
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
PPTX
AEM User Group: India Chapter Kickoff Meeting
jennaf3
 
PDF
SAP Firmaya İade ABAB Kodları - ABAB ile yazılmıl hazır kod örneği
Salih Küçük
 
PDF
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
PDF
Revenue streams of the Wazirx clone script.pdf
aaronjeffray
 
PDF
Top Agile Project Management Tools for Teams in 2025
Orangescrum
 
PPTX
Tally software_Introduction_Presentation
AditiBansal54083
 
PDF
4K Video Downloader Plus Pro Crack for MacOS New Download 2025
bashirkhan333g
 
PDF
SciPy 2025 - Packaging a Scientific Python Project
Henry Schreiner
 
PDF
유니티에서 Burst Compiler+ThreadedJobs+SIMD 적용사례
Seongdae Kim
 
PDF
[Solution] Why Choose the VeryPDF DRM Protector Custom-Built Solution for You...
Lingwen1998
 
PPTX
Tally_Basic_Operations_Presentation.pptx
AditiBansal54083
 
PPTX
Hardware(Central Processing Unit ) CU and ALU
RizwanaKalsoom2
 
PDF
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
 
PDF
Alarm in Android-Scheduling Timed Tasks Using AlarmManager in Android.pdf
Nabin Dhakal
 
PDF
Driver Easy Pro 6.1.1 Crack Licensce key 2025 FREE
utfefguu
 
Open Chain Q2 Steering Committee Meeting - 2025-06-25
Shane Coughlan
 
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 
iTop VPN With Crack Lifetime Activation Key-CODE
utfefguu
 
Help for Correlations in IBM SPSS Statistics.pptx
Version 1 Analytics
 
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
AEM User Group: India Chapter Kickoff Meeting
jennaf3
 
SAP Firmaya İade ABAB Kodları - ABAB ile yazılmıl hazır kod örneği
Salih Küçük
 
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
Revenue streams of the Wazirx clone script.pdf
aaronjeffray
 
Top Agile Project Management Tools for Teams in 2025
Orangescrum
 
Tally software_Introduction_Presentation
AditiBansal54083
 
4K Video Downloader Plus Pro Crack for MacOS New Download 2025
bashirkhan333g
 
SciPy 2025 - Packaging a Scientific Python Project
Henry Schreiner
 
유니티에서 Burst Compiler+ThreadedJobs+SIMD 적용사례
Seongdae Kim
 
[Solution] Why Choose the VeryPDF DRM Protector Custom-Built Solution for You...
Lingwen1998
 
Tally_Basic_Operations_Presentation.pptx
AditiBansal54083
 
Hardware(Central Processing Unit ) CU and ALU
RizwanaKalsoom2
 
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
 
Alarm in Android-Scheduling Timed Tasks Using AlarmManager in Android.pdf
Nabin Dhakal
 
Driver Easy Pro 6.1.1 Crack Licensce key 2025 FREE
utfefguu
 
Ad

Exception guidelines in c#

  • 1. EXCEPTION GUIDELINES IN C# AHMED HELMY | SENIOR SOFTWARE DEVELOPER
  • 2. AGENDA  Why Handle Errors?  Error Codes Drawbacks  Exceptions  Introducing Exceptions  Why Exceptions?  Exception Types  Understanding Exception Handling  Guidelines  Throw Exception Guidelines  Exception Message Guidelines  Catch Exception Guidelines  Finally Block Guidelines  Custom Exceptions Guidelines  Expensive Exceptions  Guards  References & Discussion
  • 3. WHY HANDLE ERRORS  Prevent program crashes  Chance to fix/retry  Meaningful Message  Graceful exit  Opportunity to log error “Good error handling code helps future maintainers understand what possible error conditions may occur and how they can be handled.” – Jason Roberts
  • 4. ERROR CODES DRAWBACKS  Need to add if/switch statements every time method is called to check return codes  Errors do not “bubble up” the call stack  How do you deal with system errors?  Out of memory  Access violations  How do you return an error from a constructor? “Exceptions are the primary means of reporting errors in frameworks” - Microsoft
  • 5. INTRODUCING EXCEPTIONS  System.Exception  Generated with the “throw” statement  Different exception classes represent different errors  Exception classes can contain additional error information  Different exceptions can be handled differently “An exception is any error condition or unexpected behavior that is encountered by an executing program” – Microsoft Documentation
  • 6. WHY EXCEPTIONS?  Don’t need to know all error / success codes  Don’t need if / switch statements everywhere method is called  More readable  No magic numbers / constants  Exceptions can bubble up  Catch exceptions higher up / in one place  Handle system errors  Generate exceptions from constructors
  • 7. EXCEPTION TYPES  Standard exceptions provided by the .NET Framework ( System )  . NET Runtime (CLR) - . NET Framework  OutOfMemory  StackOverflow  Exceptions provided by framework / library authors ( Third party )  JsonSerialization  Custom application exceptions ( Your code )  RulesEngine
  • 10. THROWING EXCEPTIONS  Throw an Exception  Understanding the Stack Trace
  • 11. THROW EXCEPTION GUIDELINE  DO specify the inner exception when wrapping exceptions.  DO use an empty throw statement (throw;).  Do not use exceptions for normal flow of control, if possible [Microsoft]  E.g. input validation  You expect input to invalid sometimes  Not an exceptional situation  Part of expected logic flow  IsValid(xxx) method(s)  DO NOT throw a System.Exception or System.ApplicationException.  DO NOT have public members that return exceptions as the return value or an `out` parameter  DO NOT throw exceptions from Exception Filter blocks as it returns false and it will be difficult to debug
  • 12. EXCEPTION MESSAGE GUIDELINES  Describes the reason for the exception  Written for developer who going to handling the exception  Should completely describe the error, and how to correct error (where possible / applicable)  May sometimes be shown to end-user  May sometimes be logged  Correct grammar  Correct punctuation  Correct spelling  End sentences with full stop  Consider error message localization  Should not include passwords, security, or sensitive data
  • 13. CATCH EXCEPTION  Catching Exceptions (Try, Catch, Finally)  Catching Different Exception Types  Re-throwing Exceptions  Catching and Wrapping Exceptions  Filtering Catch Blocks with Exception Filters  Global Exception Handling
  • 14. CATCH EXCEPTION GUIDELINES  Catch only exceptions that you can handle  Catch only little code that you need  Catch exception only once per thread (DO NOT over-catch)  Use Exception Logging Libraries  CONSIDER terminating the process by calling `System.Environemt.FailFast` instead of throwing an exception if your code encounters a situation where it is unsafe for further execution [Microsoft]  DO NOT Handle Exceptions inside loops  DO NOT hide (bury) exceptions you don’t fully handle  Do not add a catch block that does nothing or just re-throws  May just be to log the error  Usually bad practice to ignore (swallow / trap) exceptions  AVOID catching System.Exception or System.SystemException except in top-level exception handlers that perform final cleanup operations before rethrowing the exception.
  • 15. FINALLY BLOCK GUIDELINES  AVOID explicitly throwing exceptions from inside the block  Implicitly thrown exceptions resulting from calling methods that throw are acceptable  Use for cleanup  E.g. calling Dispose()
  • 17. CUSTOM EXCEPTIONS GUIDELINES  Naming convention: …Exception  Implement standard 3 constructors  Add additional properties where needed  Never inherit from ApplicationException class  Inherit from System.Exception (or your other custom exception)  Keep the number of custom exception types a minimum  Wrap inner exception if appropriate  Interfacing with external API, DLL, service  Use existing predefined .NET exception types where applicable, e.g.  InvalidOperationException if property set/method call is not appropriate for current state  ArgumentException (or derived) for invalid parameters  Don’t use custom (or existing) exceptions for normal (non exceptional) logic flow
  • 18. EXPENSIVE EXCEPTIONS  CONSIDER performance overhead of throwing and handling exceptions  Throw rates above 100 per second are likely to noticeably impact most application’s performance  Huge StackTrace
  • 19. GUARDS  Design code to avoid exceptions  Framework designers should design APIs so users can write code that does not throw exceptions  Tester-Doer Pattern  Try-Parse Pattern  Instead of using `int Parse(string input)` use `bool TryParse(string input, out int result)`  Check connection state before trying to close it `if(cn.State != ConnectionState.Closed) { cn.Close(); }`  Consider returning null (or null object pattern) for extremely common errors  Use Check and Guard clauses
  • 20. REFERENCES & DISCUSSION  Error Handling in C# with Exceptions by Jason Roberts  Microsoft Documentation [Exceptions]  Illustrated C# 2012 [Book]

Editor's Notes

  • #11: Demo
  • #12: DO use an empty throw statement (throw;) when rethrowing the same exception rather than passing the exception as an argument to throw. DO throw ArgumentException or one of its subtypes if bad arguments are passed to a member. Prefer the most derived exception type (ArgumentNullException, for example), if applicable. DO use nameof for the paramName argument passed into argument exception types like ArgumentException, ArgumentOutOfRangeException, and ArgumentNullException that take such a parameter. DO set the ParamName property when throwing an ArgumentException or one of the subclasses. DO document all exceptions thrown by publicly callable members because of a violation of the member contract (rather than a system failure) and treat them as part of your contract Exceptions that are a part of the contract should not change from one version to the next (i.e., exception type should not change, and new exceptions should not be added). DO NOT throw a NullRefernceException, favoring ArgumentNullException instead when a value is unexpectedly null. DO NOT have public members that return exceptions as the return value or an `out` parameter Returning exceptions from public APIs instead of throwing them defeats many of the benefits of exception-based error reporting.
  • #20: X DO NOT use exceptions for the normal flow of control, if possible. Except for system failures and operations with potential race conditions, framework designers should design APIs so users can write code that does not throw exceptions. For example, you can provide a way to check preconditions before calling a member so users can write code that does not throw exceptions. The member used to check preconditions of another member is often referred to as a tester, and the member that actually does the work is called a doer. There are cases when the Tester-Doer Pattern can have an unacceptable performance overhead. In such cases, the so-called Try-Parse Pattern should be considered (see Exceptions and Performance for more information).