Download presentation
Presentation is loading. Please wait.
1
Partnership
2
Exception handling guidelines
Basic ex. handling patterns Guidelines and best practices Anti-patterns, or not ?! Exception handling application block
3
Introduction Why should we think about the exception
handling and the logging? Software maintenance (Administrators, technical support) Uniform and clean code Prevents application of having large amount of unexpected and confusing behavior
4
Exception handling patterns
Exception shielding Protects sensitive information and prevents their leaking Exception translating Wraps original exception with purpose to add some extra info, or to adapt exception to the layer above. Example: Used by Hibernate API (doesn’t throw the SQLException, hides sensitive information) Exception logging Leaves useful information about the exception which occurred
5
The typical exception handling actions
Handle it (perform retry or an additional action) Propagate it (re-throw it) Wrap it and throw a new exception Log it (Do not use Console.WriteLine or System.out to log the data) Mix of previously mentioned approaches
6
1. Make ex. handling plan in development phase
Define exception handling policy for the software architecture: Consider and divide critical parts of the architecture from non critical Put security barriers in the architecture Cover all application threads with safety nets
7
2. Avoid leaving an empty exception handler
Can hide crucial parts of scenario which caused issue Problem diagnosis can be extremely hard (sometimes only debug procedure through tool is only option)
8
3. Provide as much as possible of exception data
Exception message Exception stack trace Exception code (if available) Custom (additional) properties All inner exceptions
9
4. Take security into consideration
Hide sensitive details and information: Database type or provider Server info
10
5. Put a human readable message in the exception log
Helps technical support and administrators. Makes the log file more readable and understandable. Sometimes, raw exception message can be very confusing without some vital information for debug process.
11
6. Use built-in exceptions if applicable
Before you create a new exception class, check whether some system exception can be used. ArgumentException ArgumentNullException InvalidCastException InvalidOperationException System.IO.FileNotFoundException System.IO.PathTooLongException Etc..
12
7. Create new exceptions by following a platform guidelines
All recommended constructors should be supported Make an exception serializable(if necessary) Follow naming convention for the exception class If you chose to override built-in exception follow the same guidelines
13
8. Avoid resetting stack trace
Do not use ‘throw ex;’ to propagate further exception, use ‘throw;’ instead. ‘throw ex’ statement resets stack trace to the point of the current line execution, therefore original exception source is hidden.
14
9. Study the exception handling policy of the API you use
It’s essential to build exception handling logic above it. It’s possible that you will find unexpected behavior which requires special treatment. WCF client dispose method throws additional exception when connection is in the fault state, hiding the real exception cause that way.
15
10. Handle a specific exception close to the place of its cause
All relevant variables and resources are available, therefore the most appropriate ex. handling action can be invoked, either to sanitize exception, retry an action or simply log error data. Human readable (useful) log message can be made with all necessary data. Avoid using general exception handlers for handling specific errors.
16
Anti-patterns, or not ? Approach log and throw ?!
Handler catch (Exception ex) ?! – fine for safety net, wrong for handling specific exceptions Catch and return null – definitely a bad practice (can introduce lots of confusion) Throw from finally – hides real exception (similar to the WCF client dispose issue) Return default value for unimplemented operations in the interface - throw NotImplementedException instead Singleton implementation by the static constructor ?! Ensuring a synchronous approach to the singleton by using a queue execution
17
Enterprise library - EHAB
The Microsoft Enterprise library is a collection of reusable software components called: application blocks, designed to assist developers with common enterprise development concerns (MSDN). Exception handling Application block (EHAB) is designed to centralize exception handling code, make it configurable and helps us to design uniform and easy to change exception handling infrastructure.
18
EHAB– Main Concepts ExceptionManager – Main entry point for the exception handling functionality. ExceptionPolicyDefinition – Encapsulates one set of rules for handling exceptions. ExceptionPolicyEntry – Defines rule how to handle one specific exception type. IExceptionHandler – Defines contract (interface) for an ExceptionHandler. An ExceptionHandler contains specific handling logic.
19
EHAB - Initialization Define an exception policy by specifying appropriate policy definitions and supply it to the exception manager. Post handling actions: None – Nothing is propagated further when all exception handlers in the policy chain are done NotifyRethrow – Original exception is propagated further when all exception handlers in the policy chain are done ThrowNewException – Throws new exception, returned by the last exception handler in the chain, to upper level when all exception handlers in the policy chain are done
20
EHAB – default handlers
WrapHandler - Wraps the current exception with a new exception of a specified type. ReplaceHandler - Replaces the exception with an entirely new exception. LoggingExceptionHandler - formats the exception into a log message and writes it down in appropriate location.
21
EHAB - Usage Use either Process or HandleException method of the ExceptionManager class. Process method is used to entirely replace try – catch block but it can be used in combination with it. HandleException method is used always in combination with try – catch block and it’s called to handle a specific exception by specified policy (Gives directly a result of the exception handling policy). Use HandlingInstanceId to give a single piece of information to the user which can be used to obtain specific details of exception
22
EHAB - DEMO In demo simple user management application will be used.
Contains DAL (data access layer) layer Has simple UI interface Has exception policy defined in the ApplicationManager singleton
23
References 0/exception-handling ption-Handling-Best-Practices-in-NET us/library/dn440728(v=pandp.60).aspx tion-handling-antipatterns
24
Conclusion Always think of the exception handling and logging in design time Follow best practice for the exception handling and try to avoid anti-patterns Use the EHAB or any similar application block to have the exception handling logic centralized, uniform and easy to maintain/change
25
Thank you
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.