360 likes | 370 Views
Learn about .NET Exception Handling, its benefits, syntax, and examples - creating robust programs by resolving exceptions gracefully.
E N D
Exception Handling Ch 13
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
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
Exception Handling • Resolving exceptions so program can continue or terminate gracefully • Creating more robust and fault-tolerant programs
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
Exception Handling Syntax try { // normal code that may throw exception } catch { // exception handling code } finally { // clean-up code in any case (error or not) }
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
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
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
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
.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
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
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
Exception Properties • Message • Stores the error message associated with an Exception object
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
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);
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:
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(); }
Equivalent to ExampleObject e = new ExampleObject(); try{ e.SomeMethod();}finally{if ( e !=null) ( ( IDisposable ) e ).Dispose();} • Example in Ch 17
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