Download presentation
Presentation is loading. Please wait.
Published byStewart Curtis Modified over 9 years ago
1
ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 1 Programming in C#.NET
2
ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 2 Outline 1.Errors and Exceptions 2.Looking Into Errors And Exception Handling Lecture 8 – C# Basics VIII
3
ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 3 Errors and Exceptions Overview Looking at the exception classes Using try – catch – finally to capture exceptions Creating user-defined exceptions
4
ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 4 Looking Into Errors And Exception Handling Exception Classes
5
ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 5 Base class exception classes
6
ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 6 Base class exception classes System.SystemException System.ApplicationException StackOverflowException EndOfStreamException OverflowException
7
ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 7 Catching Exceptions try blocks - the code might encounter some serious error conditions. catch blocks - the code that deals with the various error conditions. finally blocks - the code that cleans up any resources or takes any other action that you will normally want done at the end of a try or catch block.
8
ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 8 Catching Exceptions 1.The execution flow first enters the try block. 2.If no errors occur in the try block, execution proceeds normally through the block, and when the end of the try block is reached, the flow of execution jumps to the finally block if one is present (Step 5). However, if an error does occur within the try block, execution jumps to a catch block (next step). 3.The error condition is handled in the catch block. 4.At the end of the catch block, execution automatically transfers to the finally block if one is present. 5.The finally block is executed.
9
ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 9 Catching Exceptions try { // code for normal execution } catch { // error handling } finally { // clean up }
10
ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 10 Catching Exceptions You can omit the finally block because it is optional. You can also supply as many catch blocks as you want to handle specific types of errors. You can omit the catch blocks altogether, in which case the syntax serves not to identify exceptions, but as a way of guaranteeing that code in the finally block will be executed when execution leaves the try block. This is useful if the try block contains several exit points.
11
ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 11 Catching Exceptions throw new OverflowException(); catch (OverflowException ex) { // exception handling here }
12
ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 12 Catching Exceptions try { // code for normal execution if (Overflow == true) throw new OverflowException(); // more processing if (OutOfBounds == true) throw new IndexOutOfRangeException(); // otherwise continue normal execution } catch (OverflowException ex) { // error handling for the overflow error condition } catch (IndexOutOfRangeException ex) { // error handling for the index out of range error condition } finally { // clean up }
13
ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 13 Implementing multiple catch blocks using System; namespace Wrox.ProCSharp.AdvancedCSharp { public class MainEntryPoint { public static void Main() { string userInput; while (true) { try { Console.Write("Input a number between 0 and 5 " + "(or just hit return to exit)> "); userInput = Console.ReadLine(); if (userInput == "") break; int index = Convert.ToInt32(userInput); if (index 5) throw new IndexOutOfRangeException( "You typed in " + userInput); Console.WriteLine("Your number was " + index);
14
ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 14 Implementing multiple catch blocks } catch (IndexOutOfRangeException ex) { Console.WriteLine("Exception: " + "Number should be between 0 and 5. " + ex.Message); } catch (Exception ex) { Console.WriteLine( "An exception was thrown. Message was: " + ex.Message); } catch { Console.WriteLine("Some other exception has occurred"); } finally { Console.WriteLine("Thank you"); }
15
ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 15 Implementing multiple catch blocks if (index 5) throw new IndexOutOfRangeException("You typed in " + userInput);
16
ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 16 Implementing multiple catch blocks catch (IndexOutOfRangeException ex) { Console.WriteLine( "Exception: Number should be between 0 and 5." + ex.Message); }
17
ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 17 Implementing multiple catch blocks catch (Exception ex) { Console.WriteLine("An exception was thrown. Message was: " + ex.Message); }
18
ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 18 Implementing multiple catch blocks catch { Console.WriteLine("Some other exception has occurred"); }
19
ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 19 Implementing multiple catch blocks Input a number between 0 and 5 (or just hit return to exit)> 4 Your number was 4 Thank you Input a number between 0 and 5 (or just hit return to exit)> 0 Your number was 0 Thank you Input a number between 0 and 5 (or just hit return to exit)> 10 Exception: Number should be between 0 and 5. You typed in 10 Thank you Input a number between 0 and 5 (or just hit return to exit)> hello An exception was thrown. Message was: Input string was not in a correct format. Thank you Input a number between 0 and 5 (or just hit return to exit)> Thank you
20
ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 20 Catching exceptions from other code IndexOutOfRangeException, thrown by your own code. FormatException, thrown from inside one of the base classes.
21
ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 21 System.Exception properties Data This provides you with the ability to add key/value statements to the excep- tion that can be used to supply extra information about the exception. This is a new property in the.NET Framework 2.0. HelpLink This is a link to a help file that provides more information about the exception. InnerException If this exception was thrown inside a catch block, then InnerException contains the exception object that sent the code into that catch block. Message This is text that describes the error condition. Source This is the name of the application or object that caused the exception. StackTrace This provides details of the method calls on the stack (to help track down the method that threw the exception). TargetSite This is a.NET reflection object that describes the method that threw the exception.
22
ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 22 System.Exception properties if (ErrorCondition == true) { Exception myException = new ClassmyException("Help!!!!"); myException.Source = "My Application Name"; myException.HelpLink = "MyHelpFile.txt"; myException.Data["ErrorDate"] = DateTime.Now; myException.Data.Add("AdditionalInfo", "Contact Bill from the Blue Team"); throw myException; }
23
ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 23 What happens if an exception isn't handled? FormatException IndexOutOfRangeException The answer is that the.NET runtime would catch it.
24
ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 24 Nested try blocks try { // Point A try { // Point B } catch { // Point C } finally { // clean up } // Point D } catch { // error handling } finally { // clean up }
25
ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 25 Nested try blocks Important It is perfectly legitimate to throw exceptions from catch and finally blocks.
26
ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 26 Nested try blocks To modify the type of exception thrown To enable different types of exception to be handled in different places in your code
27
ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 27 User-Defined Exception Classes The user might type the name of a file that doesn't exist. This will be caught as a FileNotFound exception. The file might not be in the correct format. There are two possible problems here. First, the first line of the file might not be an integer. Second, there might not be as many names in the file as the first line of the file indicates. In both cases, you want to trap this oddity as a custom exception that has been written specially for this purpose, ColdCallFileFormatException.
28
ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 28 User-Defined Exception Classes 4 George Washington Zbigniew Harlequin John Adams Thomas Jefferson
29
ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 29 User-Defined Exception Classes The user might type the name of a file that doesn't exist. FileNotFound exception. The file might not be in the correct format. 1.the first line of the file might not be an integer. 2.there might not be as many names in the file as the first line of the file indicates. ColdCallFileFormatException.
30
ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 30 Catching the user-defined exceptions using System; using System.IO; namespace Wrox.ProCSharp.AdvancedCSharp { class MainEntryPoint { static void Main() { string fileName; Console.Write("Please type in the name of the file " + "containing the names of the people to be cold-called > ");
31
ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 31 Catching the user-defined exceptions fileName = Console.ReadLine(); ColdCallFileReader peopleToRing = new ColdCallFileReader(); try { peopleToRing.Open(fileName); for (int i=0 ; i<peopleToRing.NPeopleToRing; i++) { peopleToRing.ProcessNextPerson(); } Console.WriteLine("All callers processed correctly"); }
32
ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 32 Catching the user-defined exceptions catch(FileNotFoundException ex) { Console.WriteLine("The file {0} does not exist", fileName); } catch(ColdCallFileFormatException ex) { Console.WriteLine( "The file {0} appears to have been corrupted", fileName); Console.WriteLine("Details of problem are: {0}", ex.Message); if (ex.InnerException != null) Console.WriteLine( "Inner exception was: {0}", ex.InnerException.Message);
33
ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 33 Catching the user-defined exceptions } catch(Exception ex) { Console.WriteLine("Exception occurred:\n" + ex.Message); } finally { peopleToRing.Dispose(); } Console.ReadLine(); }
34
ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 34 Throwing the user-defined exceptions class ColdCallFileReader :IDisposable { FileStream fs; StreamReader sr; uint nPeopleToRing; bool isDisposed = false; bool isOpen = false;
35
ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 35 Throwing the user-defined exceptions public void Open(string fileName) { if (isDisposed) throw new ObjectDisposedException("peopleToRing"); fs = new FileStream(fileName, FileMode.Open); sr = new StreamReader(fs); try { string firstLine = sr.ReadLine(); nPeopleToRing = uint.Parse(firstLine); isOpen = true; } catch (FormatException ex) { throw new ColdCallFileFormatException( "First line isn\'t }
36
ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 36 Throwing the user-defined exceptions public void ProcessNextPerson() { if (isDisposed) throw new ObjectDisposedException("peopleToRing"); if (!isOpen) throw new UnexpectedException( "Attempted to access cold call file that is not open"); try { string name; name = sr.ReadLine(); if (name == null) throw new ColdCallFileFormatException("Not enough names"); if (name[0] == 'Z')
37
ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 37 Throwing the user-defined exceptions { throw new LandLineSpyFoundException(name); } Console.WriteLine(name); } catch(LandLineSpyFoundException ex) { Console.WriteLine(ex.Message); } finally { }
38
ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 38 Throwing the user-defined exceptions public uint NPeopleToRing { get { if (isDisposed) throw new ObjectDisposedException("peopleToRing"); if (!isOpen) throw new UnexpectedException( "Attempted to access cold call file that is not open"); return nPeopleToRing; }
39
ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 39 Throwing the user-defined exceptions public void Dispose() { if (isDisposed) return; isDisposed = true; isOpen = false; if (fs != null) { fs.Close(); fs = null; }
40
ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 40 Defining the exception classes class LandLineSpyFoundException : ApplicationException { public LandLineSpyFoundException(string spyName) : base("LandLine spy found, with name " + spyName) { } public LandLineSpyFoundException( string spyName, Exception innerException) : base( "LandLine spy found with name " + spyName, innerException) { }
41
ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 41 Defining the exception classes class ColdCallFileFormatException : ApplicationException { public ColdCallFileFormatException(string message) : base(message) { } public ColdCallFileFormatException( string message, Exception innerException) : base(message, innerException) { }
42
ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 42 Defining the exception classes class UnexpectedException : ApplicationException { public UnexpectedException(string message) : base(message) { } public UnexpectedException(string message, Exception innerException) : base(message, innerException) { }
43
ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 43 Defining the exception classes 49 George Washington Zbigniew Harlequin John Adams Thomas Jefferson
44
ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 44 Defining the exception classes MortimerColdCall Please type in the name of the file containing the names of the people to be cold- called > people.txt George Washington LandLine spy found, with name Zbigniew Harlequin John Adams Thomas Jefferson All callers processed correctly
45
ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 45 Defining the exception classes MortimerColdCall Please type in the name of the file containing the names of the people to be cold- called > people2.txt George Washington LandLine spy found, with name Zbigniew Harlequin John Adams Thomas Jefferson The file people2.txt appears to have been corrupted Details of the problem are: Not enough names
46
ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 46 Defining the exception classes MortimerColdCall Please type in the name of the file containing the names of the people to be cold- called > people3.txt The file people3.txt does not exist
47
ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 47 Summary This chapter took a close look at the rich mechanism C# has for dealing with error conditions through exceptions.This chapter took a close look at the rich mechanism C# has for dealing with error conditions through exceptions. You are not limited to the generic error codes that could be output from your code, but you have the ability to go in and uniquely handle the most granular of error conditions.You are not limited to the generic error codes that could be output from your code, but you have the ability to go in and uniquely handle the most granular of error conditions. Sometimes these error conditions are provided to you through the.NET Framework itself, but at other times, you might want to go in and code your own error conditions as was shown in this chapter.Sometimes these error conditions are provided to you through the.NET Framework itself, but at other times, you might want to go in and code your own error conditions as was shown in this chapter. In either case, you have a lot of ways of protecting the workflow of your applications from unnecessary and dangerous faults.In either case, you have a lot of ways of protecting the workflow of your applications from unnecessary and dangerous faults.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.