Docsity

Error Handling with Exceptions in .NET: Syntax and Best Practices, Slides of Advanced Algorithms

Partial preview of the text

Download Error Handling with Exceptions in .NET: Syntax and Best Practices and more Slides Advanced Algorithms in PDF only on Docsity!

Exceptions

Error Handling

in .NET

Error Handling

๏‚— Old way (Win32 API and COM):

MyFunction() { error_1 = doSomething(); if (error_1) display error else { continue processing if (error_2) display error else continue processing } }

Syntax

try { // code that requires common cleanup or // exception-recovery operations } catch (InvalidOperationException) { //code that recovers from an InvalidOperationException // (or any exception type derived from it) } catch ( SomeOtherException ) { // code that recovers from an SomeOtherException // (or any exception type derived from it) } catch { // code that recovers from any kind of exception // when you catch any exception, you usually re-throw throw; } finally { // code that cleans up any operations started // within the try block. This code ALWAYS executes. } Docsity.com

try block

  • A try block contains code that requires common cleanup or

exception-recovery operations.

  • The cleanup code should be put in a single finally block.
  • The exception recovery code should be put in one or more catch blocks. - Create one catch block for each kind of type you want to handle.
  • A try block must have at least one catch or finally

block.

catch block

๏‚— Once the catch block that matches the exception is

found, you have 3 choices:

  1. Re-throw the same exception, notifying the higher-up call stack of the exception
  2. Throw a different exception, giving richer exception information to code higher-up in the call stack
  3. Let the code continue from the bottom of the catch block ๏‚— In choices 1-2, an exception is thrown and code starts looking for a catch block whose type matches the exception thrown ๏‚— In choice 3, the finally block is executed ๏‚— You can also specify a variable name like catch(Exception e) to access information specific to the exception.

finally block

๏‚— The CLR does not completely eliminate memory leaks. Why?

๏‚— Even though GC does automatic memory clean-up, it only cleans up if there are no references kept on the object.

๏‚— Even then there may be a delay until the memory is required.

๏‚— Thus, memory leaks can occur if programmers inadvertently keep references to unwanted objects.

๏‚— C# provides the finally block, which is guaranteed to execute regardless of whether an exception occurs. ๏‚— If the try block executes without throwing, the finally block executes. ๏‚— If the try block throws an exception, the finally block still executes regardless of whether the exception is caught. ๏‚— This makes the finally block ideal to release resources from the corresponding try block.

๏‚— Example: UsingExceptions.cs

using

๏‚—The using statement simplifies writing code in which

you obtain a resource.

๏‚—The general form of a using statement is:

using ( ExampleObject e = new ExampleObject() ) { e.SomeMethod(); }

๏‚—This using statement code is equivalent to:

{ ExampleObject e = new ExampleObject(); try { e.SomeMethod(); } finally { if ( e != null ) ( ( IDisposable ) e ).Dispose(); } }

System.Exception

๏‚— In .NET, only objects of class Exception and its derived

classes may be thrown and caught.

๏‚— Exceptions thrown in other .NET languages can be caught with the general catch clause.

๏‚— Class Exception is the base class of .NETโ€™s exception class hierarchy.

๏‚— A catch block can use a base-class type to catch a hierarchy of related exceptions.

๏‚— A catch block that specifies a parameter of type Exception can catch all exceptions.

Common .NET Exceptions

๏‚— The CLR generates SystemExceptions, derived from class Exception, which can occur at any point during program execution.

๏‚— If a program attempts to access an out-of-range array index , the CLR throws an exception of type IndexOutOfRangeException.

๏‚— Attempting to use a null reference causes a NullReferenceException.

FCL-Defined Exceptions

๏‚— System.Exception ๏‚— System.ApplicationException ๏‚— System.SystemException ๏‚— System.AccessViolationException ๏‚— System.ArgumentException ๏‚— System.ArgumentNullException ๏‚— System.ArgumentOutOfRangeException ๏‚— System.FormatException ๏‚— System.IndexOutOfRangeException ๏‚— System.InvalidCastException ๏‚— System.IO.IOException ๏‚— System.IO.FileNotFoundException ๏‚— System.NotImplementedException ๏‚— System.NullReferenceException ๏‚— System.OutOfMemoryException Docsity.com

What are Exceptions?

๏‚— They are not an โ€œ exceptional event โ€, a rare event that occurs.

๏‚— They are not just errors.

๏‚— They are specific results returned when a method could not complete its task.

๏‚— Example: when should Transfer throw? public class Account { public void Transfer(Account from, Account to, decimal amount) { โ€ฆ } }

๏‚— When the Transfer method detects any of such possible conditions and cannot transfer the money, then it should notify the caller that it failed by throwing an exception.

Choosing the Exception to throw

๏‚— When implementing your own methods, you should

throw an exception when the method cannot complete

its task.

๏‚— Associating each type of malfunction with an

appropriately named exception class improves

program clarity.

1. What Exception-derived type are you going to throw?

๏‚— You must select a meaningful type ๏‚— You can select a type defined in FCL that matches your semantics ๏‚— If not, you may need to define your own type ๏‚— Your exception type hierarchy should be shallow and wide: that is, create as few base classes as possible

2. What string message are you going to pass to the

exception typeโ€™s constructor?

๏‚— If the exception is handled, no one will see this exception message. ๏‚— If the exception is unhandled, then the code will probablyDocsity.com

User-Defined Exception Example

โ€ข SquareRootTest

Do not catch everything!

try { // code that might failโ€ฆ } catch (Exception) { โ€ฆ }

  • How can you write code that can recover from all situations???
  • A class library should never ever swallow all exceptions. The application should get a chance to handle the exception.
  • You can catch all exceptions only if you are going to process it and re-throw it again.