what 抯 wrong with return codes? most programmers have probably written code that looked like this: bool success =callfunction(); if (!success) { //process the error } this works okay, but every return value has to be checked for an error. if the above was written as callfunction(); any error return would be thrown away. that抯 where bugs come from. there are many different models for communicating status; some functions may return an hresult , some may return a boolean value, and others may use some other mechanism. in the .net runtime world, exceptions are the fundamental method of han-dling error conditions. exceptions are nicer than return codes because they can抰 be silently ignored.
trying and catching to deal with exceptions, code needs to be organized a bit differently. the sections of code that might throw exceptions are placed in a try block, and the code to handle exceptions in the try block is placed in a catch block. here抯 an example:
using system; class test { static int zero =0; public static void main() { //watch for exceptions here try { int j =22 /zero; } //exceptions that occur in try are transferred here catch (exception e) { console.writeline("exception "+e.message); } console.writeline("after catch"); } }
the try block encloses an expression that will generate an exception. in this case, it will generate an exception known as dividebyzeroexceptio . when the division takes place, the .net runtime stops executing code and searches for a try block surrounding the code in which the exception took place. when it finds a try block, it then looks for associated catch blocks. if it finds catch blocks, it picks the best one (more on how it determines which one is best in a minute), and executes the code within the catch block. the code in the catch block may process the event or rethrow it. the example code catches the exception and writes out the message that is contained within the exception object. the exception hierarchy all c# exceptions derive from the class named exception , which is part of the common language runtime 1 . when an exception occurs, the proper catch block is determined by matching the type of the exception to the name of the exception mentioned. a catch block with an exact match wins out over a more general exception. returning to the example: using system; class test { static int zero =0; public static void main() { try { int j =22 /zero; } //catch a specific exception catch (dividebyzeroexception e) { console.writeline("dividebyzero {0}",e); } //catch any remaining exceptions catch (exception e) { console.writeline("exception {0}",e); } } } the catch block that catches the dividebyzeroexception is the more specific match, and is therefore the one that is executed. this example is a bit more complex:
using system; class test { static int zero =0; static void afunction() { int j = 22 / zero; //the following line is never executed. console.writeline("in afunction()"); } public static void main() { try { afunction(); } catch (dividebyzeroexception e) { console.writeline("dividebyzero {0}",e); } } } what happens here? when the division is executed, an exception is generated. the runtime starts searching for a try block in afunction(), but it doesn抰 find one, so it jumps out of afunction(), and checks for a try in main(). it finds one, and then looks for a catch that matches. the catch block then executes. sometimes, there won抰 be any catch clauses that match. using system; class test { static int zero =0; static void afunction() { try { int j =22 /zero; } //this exception doesn't match catch (argumentoutofrangeexception e) { console.writeline("outofrangeexception:{0}",e); } console.writeline("in afunction()"); } public static void main() { try { afunction(); } //this exception doesn't match catch (argumentexception e) { console.writeline("argumentexception {0}",e); } } } neither the catch block in afunction()nor the catch block in main()matches the exception that抯 thrown. when this happens, the exception is caught by the "last chance" exception handler. the action taken by this handler depends on how the runtime is configured, but it will usually bring up a dialog box containing the excep-tion information and halt the program. passing exceptions on to the caller it抯 sometimes the case that there抯 not much that can be done when an exception occurs; it really has to be handled by the calling function. there are three basic ways to deal with this, which are named based on their result in the caller: caller beware, caller confuse, and caller inform. caller beware the first way is to merely not catch the exception. this is sometimes the right design decision, but it could leave the object in an incorrect state, causing problems when the caller tries to use it later. it may also give insufficient information to the caller. caller confuse the second way is to catch the exception, do some cleanup, and then rethrow the exception: using system; public class summer { int sum =0; int count =0; float average; public void doaverage() { try { average =sum /count; } catch (dividebyzeroexception e) { //do some cleanup here throw e; } } } class test { public static void main() { summer summer =new summer(); try { summer.doaverage(); } catch (exception e) { console.writeline("exception {0}",e); } } } this is usually the minimal bar for handling exceptions; an object should always maintain a valid state after an exception. this is called caller confuse because while the object is in a valid state after the exception occurs, the caller often has little information to go on. in this case, the exception information says that a dividebyzeroexception occurred somewhere in the called function, without giving any insight into the details of the exception or how it might be fixed. sometimes this is okay if the exception passes back obvious information. caller inform in caller inform, additional information is returned for the user. the caught exception is wrapped in an exception that has additional information. using system; public class summer { int sum =0; int count =0; float average; public void doaverage() { try { average =sum /count; } catch (dividebyzeroexception e) { //wrap exception in another one, //adding additional context. throw (new dividebyzeroexception( "count is zero in doaverage()",e)); } } } public class test { public static void main() { summer summer =new summer(); try { summer.doaverage(); } catch (exception e) { console.writeline("exception:{0}",e); } } } when the dividebyzeroexception is caught in the doaverage()function, it is wrapped in a new exception that gives the user additional information about what caused the exception. usually the wrapper exception is the same type as the caught exception, but this might change depending on the model presented to the caller. this program generates the following output: exception:system.dividebyzeroexception:count is zero in doaverage()---> system.dividebyzeroexception at summer.doaverage() at summer.doaverage() at test.main() ideally, each function that wants to rethrow the exception will wrap it in an excep-tion with additional contextual information. user-defined exception classes one drawback of the last example is that the caller can抰 tell what exception hap-pened in the call to doaverage()by looking at the type of the exception. to know that the exception was because the count was zero, the expression message would have to be searched for the string is zero ". that would be pretty bad, since the user wouldn抰 be able to trust that the text would remain the same in later versions of the class, and the class writer wouldn抰 be able to change the text. in this case, a new exception class can be created. using system; public class countiszeroexception:exceptio { public countiszeroexception() { } public countiszeroexception(string message) :base(message) { } public countiszeroexception(string message,exception inner) :base(message,inner) { } } public class summer { int sum =0; int count =0; float average; public void doaverage() { if (count ==0) throw(new countiszeroexception("zero count in doaverage")); else average =sum /count; } } class test { public static void main() { summer summer =new summer(); try { summer.doaverage(); } catch (countiszeroexception e) { console.writeline("countiszeroexception:{0}",e); } } }
doaverage()now determines whether there would be an exception (whether count is zero), and if so, creates a countiszeroexception and throws it. finally sometimes, when writing a function, there will be some cleanup that needs to be done before the function completes, such as closing a file. if an exception occurs, the cleanup could be skipped: using system; using system.io; class processor { int count; int sum; public int average; void calculateaverage(int countadd,int sumadd) { count +=countadd; sum +=sumadd; average =sum /count; } public void processfile() { filestream f =new filestream("data.txt",filemode.open); try { streamreader t =new streamreader(f); string line; while ((line =t.readline())!=null) { int count; int sum; count =int32.fromstring(line); line =t.readline(); sum =int32.fromstring(line); calculateaverage(count,sum); } f.close(); } //always executed before function exit,even if an //exception was thrown in the try. finally { f.close(); } } } class test { public static void main() { processor processor =new processor(); try { processor.processfile(); } catch (exception e) { console.writeline("exception:{0}",e); } } }
this example walks through a file, reading a count and sum from a file and using it to accumulate an average. what happens, however, if the first count read from the file is a zero? if this happens, the division in calculateaverage()will throw a dividebyzero- exception , which will interrupt the file-reading loop. if the programmer had written the function without thinking about exceptions, the call to file.close() would have been skipped, and the file would have remained open. the code inside the finally block is guaranteed to execute before the exit of the function, whether there is an exception or not. by placing the file.close()call in the finally block, the file will always be closed. efficiency and overhead in languages without garbage collection, adding exception handling is expensive, since all objects within a function must be tracked to make sure that they are properly destroyed if an exception is thrown. the required tracking code both adds execution time and code size to a function. in c#, however, objects are tracked by the garbage collector rather than the compiler, so exception handling is very inexpensive to implement and imposes little runtime overhead on the program when the exceptional case doesn抰 occur. design guidelines exceptions should be used to communicate exceptional conditions. don抰 use them to communicate events that are expected, such as reaching the end of a file. in the normal operation of a class, there should be no exceptions thrown. conversely, don抰 use return values to communicate information that would be better contained in an exception. if there抯 a good predefined exception in the system namespace that describes the exception condition梠ne that will make sense to the users of the class梪se that one rather than defining a new exception class, and put specific information in the message. if the user might want to differentiate one case from others where that same exception might occur, then that would be a good place for a new excep-tion class. finally, if code catches an exception that it isn抰 going to handle, consider whether it should wrap that exception with additional information before rethrowing it.