ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 1 Programming in C#.NET.

Slides:



Advertisements
Similar presentations
(Using.NET Platform) Note: Most of the material in these slides have been adapted from MSDN and wikipedia. By Muhammad Ali.
Advertisements

Exceptions: when things go wrong. Various sources of error public static doSomething() { int i = 3.0; while(!done); { int i = false } ) Syntactic errors.
COMPUTER PROGRAMMING I Essential Standard 5.02 Understand Breakpoint, Watch Window, and Try And Catch to Find Errors.
Error Handling in.NET Exceptions. Error Handling Old way (Win32 API and COM): MyFunction() { error_1 = doSomething(); if (error_1) display error else.
CSM-Java Programming-I Spring,2005 Exceptions Lesson - 7.
CS102--Object Oriented Programming
Exceptions Don’t Frustrate Your User – Handle Errors KR – CS 1401 Spring 2005 Picture – sysprog.net.
COMP 121 Week 5: Exceptions and Exception Handling.
Try…Catch…Finally Blocks ( continued ) Generic catch clause –Omit argument list with the catch –Any exception thrown is handled by executing code within.
C# Programming: From Problem Analysis to Program Design1 Debugging and Handling Exceptions C# Programming: From Problem Analysis to Program Design 3 rd.
Mahmoud Rafeek Alfarra Computer Programming || Chapter 2: Exception handling.
Chapter 8Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 8 l Basic Exception Handling »the mechanics of exceptions l.
Exception Handling1. 2 Exceptions  Definition  Exception types  Exception Hierarchy  Catching exceptions  Throwing exceptions  Defining exceptions.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
Copyright © 2012 Pearson Education, Inc. Chapter 8 Exception Handling.
Exceptions Briana B. Morrison CSE 1302C Spring 2010.
Handling Errors during the Program Execution Svetlin Nakov Telerik Corporation
Understand Error Handling Software Development Fundamentals LESSON 1.4.
Microsoft VB 2005: Reloaded, Advanced Chapter 5 Input Validation, Error Handling, and Exception Handling.
CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 1 CPSC150 Exceptions When things.
Exceptions Used to signal errors or unexpected situations to calling code Should not be used for problems that can be dealt with reasonably within local.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Exception Handling An Exception is an indication of a problem that occurs during a program’s execution. Exception handling enables the programmer to create.
Chapter 15 Strings String::Concat String::CompareTo, Equals, == If( string1 == S”Hello”) String1->Equals(S”Hello”) String1->CompareTo(S”Hello”) CompareTo.
Exceptions. 2 Objectives Introduce C# exception handling –library exception types –custom exceptions Describe keywords used for exception handling –try.
Exceptions Objectives At the conclusion of this lesson, students should be able to Explain the need for exceptions Correctly write programs that use.
 2006 Pearson Education, Inc. All rights reserved Exception Handling.
Exception Error handling. Exception 4 n An unusual occurrence during program execution that requires immediate handling n Errors are the most common type.
Exceptions. Many problems in code are handled when the code is compiled, but not all Some are impossible to catch before the program is run  Must run.
Exceptions COMPSCI 105 S Principles of Computer Science.
Dr. Abraham. Exception Any problem that VB or OS could not handle Robust program A program that performs well not only under ordinary conditions but also.
 2002 Prentice Hall. All rights reserved. 1 Exception Handling Overview Exception handling –Enable clear, robust and more fault-tolerant programs –Process.
1 Chapter Eight Exception Handling. 2 Objectives Learn about exceptions and the Exception class How to purposely generate a SystemException Learn about.
Object Oriented Programming
And other languages…. must remember to check return value OR, must pass label/exception handler to every function Caller Function return status Caller.
1 CSC241: Object Oriented Programming Lecture No 27.
COMPUTER PROGRAMMING 2 Exceptions. What are Exceptions? Unexpected events that happen when the code is executing (during runtime). Exceptions are types.
Pemrograman VisualMinggu …12… Page 1 MINGGU Ke Duabelas Pemrograman Visual Pokok Bahasan: Exception Handling Tujuan Instruksional Khusus: Mahasiswa dapat.
PROGRAMMING IN VISUAL BASIC.NET VISUAL BASIC BUILDING BLOCKS Bilal Munir Mughal 1 Chapter-5.
Exceptions Programming in C# Exceptions CSE 494R (proposed course for 459 Programming in C#) Prof. Roger Crawfis.
Exceptions Syntax, semantics, and pragmatics Exceptions1.
VB.Net - Exceptions Copyright © Martin Schray
Introduction to Exception Handling and Defensive Programming.
Reference: Lecturer Lecturer Reham O. Al-Abdul Jabba lectures for cap211 Files and Streams- I.
Computer Programming with JAVA Chapter 8. Exception Handling Basic Exception Handling the mechanics of exceptions Defining and Using Exceptions some "simple"
Exceptions and Assertions Chapter 15 – CSCI 1302.
11. EXCEPTION HANDLING Rocky K. C. Chang October 18, 2015 (Adapted from John Zelle’s slides)
CS212: Object Oriented Analysis and Design Lecture 19: Exception Handling.
Exception-Handling Fundamentals  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of.
IMS 3253: Validation and Errors 1 Dr. Lawrence West, MIS Dept., University of Central Florida Topics Validation and Error Handling Validation.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
Exception Handling SWE 344 Internet Protocols & Client Server Programming.
Exception Handling How to handle the runtime errors.
C# Exceptions 1 CNS 3260 C#.NET Software Development.
Programming Fundamentals Exceptions Jim Warren – COMPSCI 280 S Enterprise Software Development.
Exception Handling. VB.NET has an inbuilt class that deals with errors. The Class is called Exception. When an exception error is found, an Exception.
ECE122 L23: Exceptions December 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions.
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.
Lecture 5: Exception Handling and Text File I/O Michael Hsu CSULA.
Lecture 11 Dr. Eng. Ibrahim El-Nahry Exception Handling.
Chapter 10 – Exception Handling
Syntax, semantics, and pragmatics
Creating and Modifying Text part 2
Indexer AKEEL AHMED.
Exception Handling.
CNS 3260 C# .NET Software Development
Exceptions Problems in a Java program may cause exceptions or errors representing unusual or invalid processing. An exception is an object that defines.
Part B – Structured Exception Handling
Exception Handling.
Exception Handling Imran Rashid CTO at ManiWeber Technologies.
Presentation transcript:

ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 1 Programming in C#.NET

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

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

ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 4 Looking Into Errors And Exception Handling Exception Classes

ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 5 Base class exception classes

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

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.

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.

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 }

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.

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 }

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 }

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);

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"); }

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);

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); }

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); }

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"); }

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

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.

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.

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; }

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.

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 }

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.

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

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.

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

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.

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 > ");

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"); }

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);

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(); }

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;

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 }

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')

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 { }

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; }

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; }

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) { }

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) { }

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) { }

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

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

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

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

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.