The Role of .NET Exception Handling

Slides:



Advertisements
Similar presentations
INHERITANCE BASICS Reusability is achieved by INHERITANCE
Advertisements

METHOD OVERRIDING Sub class can override the methods defined by the super class. Overridden Methods in the sub classes should have same name, same signature.
METHOD OVERRIDING 1.Sub class can override the methods defined by the super class. 2.Overridden Methods in the sub classes should have same name, same.
Error Handling in.NET Exceptions. Error Handling Old way (Win32 API and COM): MyFunction() { error_1 = doSomething(); if (error_1) display error else.
Mahmoud Rafeek Alfarra Computer Programming || Chapter 2: Exception handling.
Chapter 11 Debugging and Handling Exceptions
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
Java Exceptions. Types of exceptions  Checked exceptions: A checked exception is an exception that is typically a user error or a problem that cannot.
Exceptions Briana B. Morrison CSE 1302C Spring 2010.
Inheritance Inheritance Reserved word protected Reserved word super
C#.NET C# language. C# A modern, general-purpose object-oriented language Part of the.NET family of languages ECMA standard Based on C and C++
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
Slides prepared by Rose Williams, Binghamton University Chapter 9 More Exception Handling.
Abstraction: Polymorphism, pt. 1 Abstracting Objects.
Differences between C# and C++ Dr. Catherine Stringfellow Dr. Stewart Carpenter.
Inheritance. Types of Inheritance Implementation inheritance means that a type derives from a base type, taking all the base type’s member fields and.
CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Ganesh Viswanathan Exception Handling in Java Course Lecture Slides 7 th July 2010 “ Admitting.
11 Values and References Chapter Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables.
REFACTORING Lecture 4. Definition Refactoring is a process of changing the internal structure of the program, not affecting its external behavior and.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
 2002 Prentice Hall. All rights reserved. 1 Exception Handling Overview Exception handling –Enable clear, robust and more fault-tolerant programs –Process.
220 FINAL TEST REVIEW SESSION Omar Abdelwahab. INHERITANCE AND POLYMORPHISM Suppose you have a class FunClass with public methods show, tell, and smile.
Introduction to Classes SWE 344 Internet Protocols & Client Server Programming.
BIM313 – Advanced Programming Techniques Object-Oriented Programming 1.
Java Language and SW Dev’t
PROGRAMMING IN VISUAL BASIC.NET VISUAL BASIC BUILDING BLOCKS Bilal Munir Mughal 1 Chapter-5.
CMSC 202 Exceptions. Aug 7, Error Handling In the ideal world, all errors would occur when your code is compiled. That won’t happen. Errors which.
4.1 Instance Variables, Constructors, and Methods.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
The Java Programming Language
Programming in C#. I. Introduction C# (or C-Sharp) is a programming language. C# is used to write software that runs on the.NET Framework. Although C#
CIS 3301 C# Lesson 13 Interfaces. CIS 3302 Objectives Understand the Purpose of Interfaces. Define an Interface. Use an Interface. Implement Interface.
Object Oriented Programming with C# Session: August-December 2009 Subject: C# Programming.
Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 5, page 1 Sun Certified Java 1.4 Programmer Chapter 5 Notes Gary Lance
Session 08 Module 14: Generics and Iterator Module 15: Anonymous & partial class & Nullable type.
Introduction to Exception Handling and Defensive Programming.
Polymorphic support in C# Let us now examine third pillar of OOP i.e. Polymorphism.. Recall that the Employee base class defined a method named GiveBonus(),
E FFECTIVE C# 50 Specific Ways to Improve Your C# Second Edition Bill Wagner محمد حسین سلطانی.
RIT Computer Science Dept. Goals l Inheritance l Modifiers: private, public, protected l Polymorphism.
Constructors CMSC 202. Object Creation Objects are created by using the operator new in statements such as… The following expression invokes a special.
Programming in Java CSCI-2220 Object Oriented Programming.
1 Enumerations and Structs Chapter 9. 2 Objectives You will be able to: Write programs that define and use enumeration variables. Write programs that.
1 Interfaces and Abstract Classes Chapter Objectives You will be able to: Write Interface definitions and class definitions that implement them.
Operator Overloading Week 5.
Static. 2 Objectives Introduce static keyword –examine syntax –describe common uses.
COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi.
Programming and Problem Solving With Java Copyright 1999, James M. Slack Exceptions Handling Exceptions with try and catch The finally-block The throws.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Exception-Handling Fundamentals  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of.
1 Exceptions. 2 Syntax Errors, Runtime Errors, and Logic Errors syntax errors, runtime errors, and logic errors You learned that there are three categories.
Presented by Ted Higgins, SQL Server DBA An Introduction to Object – Oriented Programming.
ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University 1 Programming in C#.NET.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Exception Handling SWE 344 Internet Protocols & Client Server Programming.
C# Fundamentals An Introduction. Before we begin How to get started writing C# – Quick tour of the dev. Environment – The current C# version is 5.0 –
Exception and Exception Handling. Exception An abnormal event that is likely to happen during program is execution Computer could run out of memory Calling.
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
9.1 CLASS (STATIC) VARIABLES AND METHODS Defining classes is only one aspect of object-oriented programming. The real power of object-oriented programming.
Lecture 11 Dr. Eng. Ibrahim El-Nahry Exception Handling.
Working with Java.
Subject Name: C# and .NET Programming Subject Code: 10CS761.
Java Programming Language
Controlling Base-Class Creation
Programming in C# Lesson 5. Exceptions..
Object Comparisons and Arrays
CIS 199 Final Review.
CMSC 202 Exceptions.
Presentation transcript:

The Role of .NET Exception Handling The Atoms of .NET Exception Handling System.Exception Base class Need and Definition Example Throwing a generic exception …..

The Role of .NET Exception hanlding Prior to .NET, error handling under the windows operating system was a confused mishmash of techniques. Many Programmers rolled their own error handling logic within the context of a given application. For example, a development team may define a set of numerical constants that represent known error conditions, and make use of them as return values. In addition to a developer’s ad-hoc techniques, the Windows API defines hundreds of error codes that comes by the way of various methods and techniques.

The Role of .NET Exception hanlding The obvious problem with these techniques is lack of symmetry. Each approach is more or less tailored to a given technology, a given language, and perhaps even a given project. In order to put up an end, .NET platform provides a standard technique to send and trap run time errors: Structured Exception Handling [SEH]. The beauty of this approach is that developers now have a unified approach to error handling, which is common to all languages targeting the .NET Universe, As an added bonus, the syntax used to throw and catch exceptions across assemblies and machine boundaries is identical. Another bonus of .NET exceptions is that fact that rather than receiving a cryptic numerical value that identifies the problem at hand, exception are objects that contain a human readable descriptions

The System.Exception Base Class All user- and system-defined exceptions ultimately derive from the System.Exception base class (which in turn derives from System.Object). Note that some of these members are virtual and may thus be overridden by derived types: public class Exception : ISerializable, _Exception { public virtual IDictionary Data { get; } protected Exception(SerializationInfo info, StreamingContext context); public Exception(string message, Exception innerException); public Exception(string message); public Exception(); public virtual Exception GetBaseException(); public virtual void GetObjectData(SerializationInfo info, StreamingContext context); public System.Type GetType(); protected int HResult { get; set; } public virtual string HelpLink { get; set; } public System.Exception InnerException { get; } public virtual string Message { get; } public virtual string Source { get; set; } public virtual string StackTrace { get; } public MethodBase TargetSite { get; } public override string ToString(); }

System.Exception base class

Contd.. The Simplest Possible Example To illustrate the usefulness of structured exception handling, we need to create a type that may throw an exception under the correct circumstances. Assume we have created a new console application project (named SimpleException) that defines two class types (Car and Radio) associated using the “has-a” relationship. The Radio type defines a single method that turns the radio’s power on or off: public class Radio { public void TurnOn(bool on) if(on) Console.WriteLine("Jamming..."); else Console.WriteLine("Quiet time..."); }

In addition to leveraging the Radio type via containment/delegation, the Car type is defined in such a way that if the user accelerates a Car object beyond a predefined maximum speed Beyond these points, the Car type has a few member variables to represent the current speed and a user supplied “pet name” as well as various constructors.

public class Car { // Constant for maximum speed. public const int maxSpeed = 100; // Internal state data. private int currSpeed; private string petName; // Is the car still operational? private bool carIsDead; // A car has-a radio. private Radio theMusicBox = new Radio(); // Constructors. public Car() {} public Car(string name, int currSp) currSpeed = currSp; petName = name; }

public void CrankTunes(bool state) { // Delegate request to inner object. theMusicBox.TurnOn(state); } // See if Car has overheated. public void Accelerate(int delta) if (carIsDead) Console.WriteLine("{0} is out of order...", petName); else currSpeed += delta; if (currSpeed > maxSpeed) Console.WriteLine("{0} has overheated!", petName); currSpeed = 0; carIsDead = true; Console.WriteLine("=> CurrSpeed = {0}", currSpeed);

Now, if we were to implement a Main() method that forces a Car object to exceed the predefined maximum speed (represented by the maxSpeed constant) as shown here: static void Main(string[] args) { Console.WriteLine("***** Creating a car and stepping on it *****"); Car myCar = new Car("Zippy", 20); myCar.CrankTunes(true); for (int i = 0; i < 10; i++) myCar.Accelerate(10); Console.ReadLine(); } The output would be as follows:

Throwing a Generic Exception The current implementation of Accelerate() displays an error message if the caller attempts to speed up the Car beyond its upper limit. To retrofit this method to throw an exception if the user attempts to speed up the automobile after it has met its maker, you want to create and configure a new instance of the System.Exception class, setting the value of the read-only Message property via the class constructor. When you wish to send the error object back to the caller, make use of the C# throw keyword. Here is the relevant code update to the Accelerate() method: public void Accelerate(int delta) { if (carIsDead) Console.WriteLine("{0} is out of order...", petName); else currSpeed += delta; if (currSpeed >= maxSpeed) carIsDead = true; currSpeed = 0;

Throwing a Generic Exception // Use "throw" keyword to raise an exception. throw new Exception(string.Format("{0} has overheated!", petName)); } else Console.WriteLine("=> CurrSpeed = {0}", currSpeed); First of all, when you are throwing an exception, it is always up to you to decide exactly what constitutes the error in question, and when it should be thrown. Here, you are making the assumption that if the program attempts to increase the speed of a car that has expired, a System.Exception type should be thrown to indicate the Accelerate() method cannot continue. Alternatively, you could implement Accelerate() to recover automatically without needing to throw an exception in the first place. By and large, exceptions should be thrown only when a more terminal condition has been met Deciding exactly what constitutes throwing an exception is a design issue you must always contend with.