1 / 36

Exception Handling

Learn about .NET Exception Handling, its benefits, syntax, and examples - creating robust programs by resolving exceptions gracefully.

pcharles
Download Presentation

Exception Handling

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Exception Handling Ch 13

  2. Exception • An indication of a problem that occurs during a program’s execution • Exception is the base class for all exceptions • Defined in the System namespace

  3. Exception Example

  4. Result

  5. Thrown Exception • Information about an exception • Name of the exception • A descriptive message that indicates the problem • The path of execution that led to the exception, method by method • DivideByZeroException • Occurs when there is a division by zero • FormatException • Occurs when the format of an argument does not meet the parameter of the invoked method

  6. Exception Handling • Resolving exceptions so program can continue or terminate gracefully • Creating more robust and fault-tolerant programs

  7. Benefits of Exception Handling • Removes error-handling code from the “main line” of the program’s execution • Intermixing program logic with error-handling logic makes programs difficult to read, modify, maintain, and debug • Improves clarity

  8. Exception Handling Example

  9. Result

  10. Exception Handling Syntax try { // normal code that may throw exception } catch { // exception handling code } finally { // clean-up code in any case (error or not) }

  11. try Block • Encloses code that might throw an exception • The code should not execute if an exception occurs • At least one catch block and/or finally block immediately after the try block

  12. catch Block • Catches and handles an exception • Executes when exception of proper type matches • Exception parameter in parentheses • Identifies the exception type and allows interaction with caught exception object • If parameter-less, can catch any exception type

  13. Uncaught Exceptions • There are no matching catch blocks • Program mostly terminates when there is an uncaught exception • If debugging in Visual Studio, application pauses and Exception Assistant appears indicating where the exception occurred

  14. Termination Model • When an exception occurs • try block terminates immediately • Program control transfers to first matching catch block • After exception is handled • Program control does not return to the throw point because the try block has expired • Flow of control proceeds to the first statement after the last catch block

  15. .NET Exception Hierarchy • ClassException • Can be used to catch all exceptions • Derived Class ApplicationException • Base class that programmers can extend to create exception classes specific to their applications • Derived Class SystemException • Mainly, this exception can be avoided if coded properly • CLR throws SystemException when it becomes unstable

  16. finally Block • Optional • Executes whether or not an exception is thrown • Typically contains resource-release code • Programs that obtain certain resources (files, network connections, etc.) must return them to avoid resource leaks

  17. finally Example

  18. Result

  19. throw Statement • Throw exceptions • Can throw exceptions from a method if something has gone wrong • The string passed through the constructor is the exception object’s error message

  20. Exception Properties • Message • Stores the error message associated with an Exception object

  21. Payroll Example publicabstractclassEmployee {publicstring FirstName { set { value = value.Trim().ToUpper(); if (value.Length < 1) thrownewApplicationException("First empty!"); foreach(char c invalue) if(c<'A' || c>'Z') thrownewApplicationException("First name must consist of letters only!"); firstNameValue = value; } // end set } // end property FirstName

  22. Test Program do { ok = true; try { Console.Write("First Name: "); employee.FirstName = Console.ReadLine(); } catch(Exception ex) { Console.WriteLine(ex.Message); ok = false; } } while (!ok);

  23. Result Welcome to the Payroll System! Add a new faculty member Is this a salaried or hourly employee (S/H)? S First Name: First name is empty! First Name: 1234 First name must consist of letters only! First Name: Min Last Name:

  24. using Statement • Different from the using directive for namespaces! • Simplifies code for obtaining a resource • Resource is released at the end using ( ExampleObject e = new ExampleObject() ) { e.SomeMethod(); }

  25. Equivalent to ExampleObject e = new ExampleObject(); try{ e.SomeMethod();}finally{if ( e !=null) ( ( IDisposable ) e ).Dispose();} • Example in Ch 17

  26. Summary • Exception • An indication of a problem that occurs during a program’s execution • Exception handling • Creating more robust, fault-tolerant programs • try … catch … finally • throw exception

More Related