Presentation is loading. Please wait.

Presentation is loading. Please wait.

Exceptions Programming in C# Exceptions CSE 494R (proposed course for 459 Programming in C#) Prof. Roger Crawfis.

Similar presentations


Presentation on theme: "Exceptions Programming in C# Exceptions CSE 494R (proposed course for 459 Programming in C#) Prof. Roger Crawfis."— Presentation transcript:

1 Exceptions Programming in C# Exceptions CSE 494R (proposed course for 459 Programming in C#) Prof. Roger Crawfis

2 Slides are not finished Not sure we will cover this topic.

3 Exceptional Situations Sometimes, runtime errors are caused by unusual situations, not programming errors For example: writing data to a file Most of the time things go uneventfully, but... The disk may be full There may be a hardware error The file may have been changed to read-only Fragile code ignores the possibility of problems Robust code anticipates such problems

4 The Traditional Method I Traditional way of handling is to use "completion codes" GET A FILENAME OPEN THE FILE IF THERE IS NO ERROR OPENING THE FILE READ SOME DATA IF THERE IS NO ERROR READING THE DATA PROCESS THE DATA WRITE THE DATA IF THERE IS NO ERROR WRITING THE DATA CLOSE THE FILE IF THERE IS NO ERROR CLOSING FILE RETURN

5 The Traditional Method II Things to notice with completion codes Almost every step may fail, except "PROCESS DATA" Program just be prepared to deal with failure Very difficult to determine "normal" actions So concerned with things that can go wrong that it is hard to tell if you are doing the right things in the right order Difficult to use if library function contains such code Function must return several error codes so that user can tell what went wrong

6 The Exceptional Method Using exceptions the code looks like this TRY TO DO THESE THINGS: GET A FILENAME OPEN THE FILE READ SOME DATA PROCESS THE DATA WRITE THE DATA CLOSE THE FILE RETURN IF ERROR OPENING THE FILE THEN... IF ERROR READING THE DATA THEN... IF ERROR WRITING THE DATA THEN... IF ERROR CLOSING THE FILE THEN...

7 Exception Advantages Compare methods of handling "bad things" Code that uses the exception strategy: Is shorter and easier to read Makes the normal logic the main focus of the method. In the completion code version, the error-handling code obscures the normal actions Allows you to decide whether to handle the problem or defer handling the error on a case-by-case basis Ideal for library-based code

8 Exception Objects In C#, when a runtime error occurs Exception The CLR sees the problem and creates an Exception System.Exception Object is from a subclass of System.Exception ApplicationException Class ApplicationException : extend & recover SystemException Class SystemException : fix by proper coding The exception object is thrown back up the call stack until a method is found that wants to catch it If it is not "caught" then the CLR runtime system prints an error message

9 Following Exceptions CLR Runtime The Main( ) method First Method Exception Thrown Here Method Calls Travel Down Exceptions Passed Up

10 Using try-catch try- catch In C#, you handle exceptions with try- catch try Put the code that may cause an exceptional situation into a “ try ” block. catch try Provide one or more “ catch ” blocks immediately following the “ try ” block catch You should provide catch blocks for all errors you want to handle. Do this by choosing to catch particular classes. catch If you don’t provide a catch block for a particular exception, then the exception will be propagated up

11 The try-catch Syntax

12 The try block try The try block consists of: try The keyword try Followed by a brace-delimited block Braces are required: part of the syntax if This is unlike loops and if statements try Inside the try block Place any number of statements that may throw an exception

13 The catch Block try Place one or more immediately following try Nothing but whitespace or comments between catch Syntax for catch block is a little tricky catch (Exception-Class [var1]) { // Handle exception 1 here } catch (Exception-Class [var2]) { // Handle exception 2 here }

14 A try-catch Example Example : DivideByZeroTest.csDivideByZeroTest.cs Find on Q: drive in folder ch11\Fig11_01 Drag and drop on F: or U: drive Convert.ToInt32() Method Convert.ToInt32() will automatically detect for invalid representation of an integer FormatException Method generates a FormatException CLR automatic detection for division by zero DivideByZeroException Occurrence will cause a DivideByZeroException

15 Now, Finally, finally When an exception is thrown catch Control jumps to the catch block that handles it Code that releases resources may be skipped Open File Read Data // Exception thrown here Close File // This is skipped. File still open try-catchfinally The try-catch has an optional finally part This will always be called Use to handle resource depletion

16

17 Throwing Exceptions try-catch-finally You aren't restricted to try-catch-finally You can throw exceptions as well Exception Must be an Exception object or a subclass if (numerator == 0) throw new Exception("Illegal numerator"); You can rethrow a caught exception as well Example: Figure 11-2, UsingExceptions.cs UsingExceptions.cs

18 Exception Object Properties Properties for a caught exception [ Properties.cs ] Properties.cs Message Message : error message associated with an exception May be a default message or customized StackTrace StackTrace : string representing the method call stack List of "pending" methods when the exception occurred The exact location is called the throw point InnerException InnerException property “Wrap” exception objects caught in code Then throw new exception types

19 Defining Your Own Exceptions Your program may have "application- specific" exceptions To define your own exception classes ApplicationException Derive a new class from ApplicationException For consistencies sake, name should end with “Exception” Should define three constructors A default constructor A constructor that receives a string argument A constructor that takes a string and an Exception argument Example: NegativeNumberException.csNegativeNumberException.cs

20 Handling Integer Overflow Traditionally, integer overflow is not a runtime error If a result is too large the answer is silently truncated int ans = 400000 * 400000 / 400000; C# allows you to change this on a calc- by-calc basis int ans = checked( 400000 * 400000 / 400000); OverflowException Throws an OverflowException unchecked() There is a matching unchecked() operator Example: Overflow.csOverflow.cs

21 Exceptions in C# Must inherit from System.Exception Standard error handling in C# Are thrown when: the code reaches a throw statement System exceptions occur (such as divide by zero) No checked exceptions or exception specifications

22 Creating an Exception Class Inherit ultimately from System.Exception public class Exception1 : System.Exception { public Exception1(string message) : base(message){} } public class SomeException : Exception1 { public SomeException(string message) : base(message){} }

23 throw statement Must throw an instance of an exception: throw(new MyException(“Error”)); May be used by itself only in a catch block: catch { throw; }

24 Catching an Exception A catch block is associated with a try block A try block may have more than one catch block catch blocks catch the exception type or any derived exception types passing through catch blocks are searched in the order they appear in the code catch blocks for specific types must come before the more general types An Empty catch clause will catch any type catch clauses don’t need a variable name catch(Exception) is ok

25 catch blocks void function1() { try { // code } catch(Exception1 ex) { } catch(Exception ex) { } // if no rethrow occurs // execution resumes here } void function1() { try { // code } catch(Exception ex) { } catch(Exception1 ex) { } } Wrong Right

26 Exception Flow Control void function1() { try { try { throw(new SomeOtherException(“Error Message”)); } catch(Exception1 ex) { } catch(Exception2 ex) { } } The exception is passed up the call-stack until a suitable handler is found

27 Exception Flow Control void function2() { try { Function1(); } catch(Exception3 ex3) { } catch(Exception2 ex4) { } catch(Exception ex) { } } If no suitable handler (catch clause) was found, the exception is passed to the calling method

28 Unhandled Exceptions If no error handler is found the application terminates Control is passed back to Windows

29 finally block Must be associated with a try block a try block may have only one finally block finally block always gets executed The appropriate catch clause is executed first

30 finally Flow Control void function1() { try { try { throw(new SomeException(“Error Message”)); } catch(Exception1 ex) { } finally { } catch(Exception2 ex) { } finally { }

31 Some Special Rules Unhandled Exception in a destructor destructor stops executing, exception is discarded, base destructor is called catch (with no parameter) will catch unmanaged exceptions from other languages

32 Library Exceptions Feel free to use these: ArithmeticException ArrayTypeMismatchException DivideByZeroException IndexOutOfRangeException InvalidCastException NullReferenceException OutOfMemoryException OverflowException StackOverflowException TypeInitializationException

33 System.Exception Class Message string message associated with the exception InnerException If this exception was generated inside an exception handler, this refers to the original exception Source Refers to the source class StackTrace String representing the call stack, file and line number

34 Breaking On Exceptions Debug | Exceptions (or Ctrl + D, E)

35 Exception Handling Provides tremendous benefits Requires a different way of thinking

36 The old way RETVAL Process(int a, int x, int y, int z) { RETVAL retval; if ((retval = function(x, y, z)) != OK) return retval; if ((retval = function2(a, y)) != OK) return retval; }

37 Option 1 void Process(int a, int x, int y, int z) { try { function(x, y, z); } catch (Exception e) { throw e; } try { function2(a, y); } catch (Exception e) { throw e; }

38 Option 2 void Process(int a, int x, int y, int z) { try { function(x, y, z); function2(a, y); } catch (Exception e) { throw e; }

39 Option 3 void Process(int a, int x, int y, int z) { function(x, y, z); function2(a, y); }

40 Exception Handling You get correct behavior by default Only catch an exception when you can do something useful for the user You can write lots of unnecessary code, but at least your code will be less robust

41 When to catch Something specific happens, and we can help try{ StreamReader s = File.OpenText(filename); StreamReader s = File.OpenText(filename);} catch (Exception e) { Console.WriteLine(“Invalid filename: {0}”, filename); Console.WriteLine(“Invalid filename: {0}”, filename);}try{ StreamReader s = File.OpenText(filename); StreamReader s = File.OpenText(filename);} catch (FileNotFoundException e) { Console.WriteLine(e); Console.WriteLine(e);}

42 try{ ExecuteBigProcess(); ExecuteBigProcess();} catch (Exception e) { log.WriteLine(e.ToString()); log.WriteLine(e.ToString()); throw; throw;}try{ ExecuteBigProcess(); ExecuteBigProcess();} catch (Exception e) { throw new MyException(“Error executing BigProcess”, e); throw new MyException(“Error executing BigProcess”, e);} When to catch We need to log or wrap an exception

43 When to catch Process would die otherwise public static void Main() { while (true) while (true) { try try { MainLoop(); MainLoop(); } catch (Exception e) catch (Exception e) { Console.WriteLine(“Exception caught, trying to continue”); Console.WriteLine(“Exception caught, trying to continue”); Console.WriteLine(e); Console.WriteLine(e); } }}

44 Finally statement If an exception is thrown and There’s something to clean up Close a file Release a DB handle Using statement makes this easier Works on anything that implements IDisposable

45 Using Statement Acquire, Execute, Release pattern Works with any IDisposable object Data access classes, streams, text readers and writers, network classes, etc. using (Resource res = new Resource()) { res.DoWork(); res.DoWork();} Resource res = new Resource(...); try { res.DoWork(); res.DoWork();} finally { if (res != null) ((IDisposable)res).Dispose(); if (res != null) ((IDisposable)res).Dispose();}

46 Using Statement static void Copy(string sourceName, string destName) { Stream input = File.OpenRead(sourceName); Stream input = File.OpenRead(sourceName); Stream output = File.Create(destName); Stream output = File.Create(destName); byte[] b = new byte[65536]; byte[] b = new byte[65536]; int n; int n; while ((n = input.Read(b, 0, b.Length)) != 0) { while ((n = input.Read(b, 0, b.Length)) != 0) { output.Write(b, 0, n); output.Write(b, 0, n); } output.Close(); output.Close(); input.Close(); input.Close();} static void Copy(string sourceName, string destName) { Stream input = File.OpenRead(sourceName); Stream input = File.OpenRead(sourceName); try { try { Stream output = File.Create(destName); Stream output = File.Create(destName); try { try { byte[] b = new byte[65536]; byte[] b = new byte[65536]; int n; int n; while ((n = input.Read(b, 0, b.Length)) != 0) { while ((n = input.Read(b, 0, b.Length)) != 0) { output.Write(b, 0, n); output.Write(b, 0, n); } } finally { finally { output.Close(); output.Close(); } } finally { finally { input.Close(); input.Close(); }} static void Copy(string sourceName, string destName) { using (Stream input = File.OpenRead(sourceName)) using (Stream input = File.OpenRead(sourceName)) using (Stream output = File.Create(destName)) { using (Stream output = File.Create(destName)) { byte[] b = new byte[65536]; byte[] b = new byte[65536]; int n; int n; while ((n = input.Read(b, 0, b.Length)) != 0) { while ((n = input.Read(b, 0, b.Length)) != 0) { output.Write(b, 0, n); output.Write(b, 0, n); } }}

47 Exceptions vs Return Codes Exceptions are meant for exceptional cases Invalid parameters Can’t perform operation Should not occur during normal program operation User interaction is a grey area

48 Using Return Values Okay if your caller always will have to check and recover from something Make sure you don’t force them to write: Shouldn’t be possible to do the wrong thing File.Open() returns null on file not found You can’t ignore this bool success = TryOperation(param1, param2); if (!success) return success; return success;

49 Summary Understand how the model works Don’t work too hard If you can’t do something useful, don’t catch

50 Exceptions Programming in C# Exceptions CSE 494R (proposed course for 459 Programming in C#) Prof. Roger Crawfis

51 XML Documentation Programming in C# XML Documentation CSE 494R (proposed course for 459 Programming in C#) Prof. Roger Crawfis

52 XML Documentation Programming in C# XML Documentation CSE 494R (proposed course for 459 Programming in C#) Prof. Roger Crawfis


Download ppt "Exceptions Programming in C# Exceptions CSE 494R (proposed course for 459 Programming in C#) Prof. Roger Crawfis."

Similar presentations


Ads by Google