Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Handling Errors and Exceptions Chapter 6. 2 Objectives You will be able to: 1. Use the try, catch, and finally statements to handle exceptions. 2. Raise.

Similar presentations


Presentation on theme: "1 Handling Errors and Exceptions Chapter 6. 2 Objectives You will be able to: 1. Use the try, catch, and finally statements to handle exceptions. 2. Raise."— Presentation transcript:

1 1 Handling Errors and Exceptions Chapter 6

2 2 Objectives You will be able to: 1. Use the try, catch, and finally statements to handle exceptions. 2. Raise exceptions from your own methods using the throw keyword. 3. Enable checking for integer overflow.

3 3 Error Processing The old way: Do Something; if (Error) { Take some action to handle error; }

4 4 Problems with the old way: New error overwrites old one. Error checking clutters the code. Makes the normal code hard to read Error codes such as -1 are not inherently meaningful. To use a function you have to know its error codes. No built-in error messages Easy to ignore errors.

5 5 Exceptions Exceptions are the modern solution to error handling. Rare example of a “good goto” Rather than completing and returning an error code when somthing goes wrong, “goto” to the caller’s error handling routine. Can propagate up the call stack.

6 6 When to Use Exception Handling Use an exception handler for unexpected problems Bad data Impossible condition Not for normal flow of control End of loop End of file Exception processing is usually very slow.

7 7 Example: Catch Block static void Main(string[ ] args) { try { int lhs = Int32.Parse(Console.ReadLine()); int rhs = Int32.Parse(Console.ReadLine()); int ans = lhs / rhs; Console.WriteLine(ans.ToString()); } catch (Exception ex) { Console.WriteLine("Error: " + ex.Message); } Console.ReadLine(); // Hold window open }

8 8 Example: Divide by Zero

9 9 Example: Input not an integer

10 10 Example: Nonnumeric Input

11 11 Example: Value Out of Range

12 The exception will propagate upward if not handled. static int Divide (int lhs, int rhs) { int ans = lhs / rhs; return ans; } static void Main(string[] args) { try { int lhs = Int32.Parse(Console.ReadLine()); int rhs = Int32.Parse(Console.ReadLine()); int ans = Divide (lhs, rhs); Console.WriteLine(ans.ToString()); } catch (Exception ex) { Console.WriteLine("Error: " + ex.Message); } 2. Divide throws exception (No handler) 1. Call function (rhs == 0) 3. Continue here

13 13 Exception Propagates Upward

14 14 You can provide multiple catch handlers try { int lhs = Int32.Parse(Console.ReadLine()); int rhs = Int32.Parse(Console.ReadLine()); int ans = lhs / rhs; Console.WriteLine(ans.ToString()); } catch (System.FormatException ex) { Console.WriteLine("Please enter a integer value."); } catch (System.DivideByZeroException ex) { Console.WriteLine("Please enter a nonzero value for divisor."); }

15 15 Checked and Unchecked Integer Arithmetic By default, integer arithmetic is unchecked. Integer overflow will not throw an exception. Overflow checking can be enabled for an entire project individual blocks of codes individual expressions

16 16 Checked and Unchecked Integer Arithmetic static void Main(string[] args) { try { int lhs = Int32.Parse(Console.ReadLine()); int rhs = Int32.Parse(Console.ReadLine()); int ans = lhs + rhs; Console.WriteLine(ans.ToString()); } catch (Exception ex) { Console.WriteLine("Error: " + ex.Message); } Console.ReadLine(); // Hold window open }

17 17 Using Unchecked Integer Arithmetic

18 18 Using Checked Integer Arithmetic static void Main(string[] args) { try { int lhs = Int32.Parse(Console.ReadLine()); int rhs = Int32.Parse(Console.ReadLine()); int ans = checked(lhs + rhs); Console.WriteLine(ans.ToString()); } catch (Exception ex) { Console.WriteLine("Error: " + ex.Message); } Console.ReadLine(); // Hold window open }

19 19 Using Checked Integer Arithmetic

20 20 A Checked Block static void Main(string[] args) { checked { try { int lhs = Int32.Parse(Console.ReadLine()); int rhs = Int32.Parse(Console.ReadLine()); int ans = lhs + rhs; Console.WriteLine(ans.ToString()); } catch (Exception ex) { Console.WriteLine("Error: " + ex.Message); } Console.ReadLine(); // Hold window open }

21 21 Checked Compiler Option To set the compiler option, right click on the project in Solution Explorer and select Properties. Then click the Advanced button

22 22 Checked Compiler Option Click here

23 23 Checked Compiler Option Now all integer arithmetic in this project will be checked. Click OK

24 24 Unchecked Source Code static void Main(string[] args) { try { int lhs = Int32.Parse(Console.ReadLine()); int rhs = Int32.Parse(Console.ReadLine()); int ans = lhs + rhs; Console.WriteLine(ans.ToString()); } catch (Exception ex) { Console.WriteLine("Error: " + ex.Message); } Console.ReadLine(); // Hold window open }

25 25 Overflow Exception

26 This is how you can return an error indication to the caller. Example: public static string monthName(int Month) { switch (Month) { case 1 : return "January"; case 2 : return "February"; //... case 12 : return "December"; default : throw new ArgumentOutOfRangeException("Bad Month"); } } Throwing Exceptions Class defined in the System namespace Creates an object of class ArgumentOutOfRangeException having error message “Bad Month”.

27 27 Why throw an exception? Library functions know what is wrong but not what to do about it. Clients know what to do but may not know what is wrong. Various clients may respond to error conditions in different ways. Library function throws an exception. Client handles it.

28 28 Writing a finally block Sometimes you need to be sure that some cleanup code is executed even if an exception is thrown and your method does not run to completion. string line; StreamReader reader = new StreamReader(@"c:\test.txt"); while ((line = reader.ReadLine()) != null) { // Do something with line. // May result in an exception. } reader.Close();

29 29 Writing a finally block If something goes wrong in the while loop and an exception is thrown, the close will not be executed. You can use a finally block to ensure that the close is executed even if an exception is thrown.

30 30 Writing a finally block StreamReader reader; try { string line; reader = new StreamReader(@"c:\test.txt"); while ((line = reader.ReadLine()) != null) { // Do something with line. // May result in an exception. } finally { if (reader != null) { reader.Close(); }

31 31 Writing a finally block Use “finally” after a “try” block for something that must be done whether or not an exception is thrown. Typically releasing resources. “finally” block goes after last “catch” block (if any)

32 32 Executing the finally block If an exception is thrown in the try block and caught locally “finally” block is executed after the catch block. and not caught locally “finally” block is executed before the exception is propagated upward. If no exception is thrown in the try block “finally” block is executed after the try block.

33 33 Summary Exception handling is an effective mechanism for dealing with errors. Supports error recovery when possible. Permits detailed, meaningful error messages. Gets error processing out of the way. Use exception handlers for unexpected problems. Not for normal “errors” such as end of file.

34 34 Handling Errors and Exceptions Assignment: Read Chapter 6 Project 1 End of Presentation


Download ppt "1 Handling Errors and Exceptions Chapter 6. 2 Objectives You will be able to: 1. Use the try, catch, and finally statements to handle exceptions. 2. Raise."

Similar presentations


Ads by Google