Error Handling in.NET Exceptions. Error Handling Old way (Win32 API and COM): MyFunction() { error_1 = doSomething(); if (error_1) display error else.

Slides:



Advertisements
Similar presentations
Chapter 17 Failures and exceptions. This chapter discusses n Failure. n The meaning of system failure. n Causes of failure. n Handling failure. n Exception.
Advertisements

Exception Handling The purpose of exception handling is to permit the program to catch and handle errors rather than letting the error occur and suffer.
CSE 1302 Lecture 21 Exception Handling and Parallel Programming Richard Gesick.
Exception Handling Chapter 15 2 What You Will Learn Use try, throw, catch to watch for indicate exceptions handle How to process exceptions and failures.
Errors and Exceptions The objectives of this chapter are: To understand the exception handling mechanism defined in Java To explain the difference between.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 15: Exception Handling.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Exception Handling Xiaoliang Wang, Darren Freeman, George Blank.
Chapter 16: Exception Handling C++ Programming: From Problem Analysis to Program Design, Fifth Edition.
Objectives In this chapter you will: Learn what an exception is Learn how to handle exceptions within a program See how a try / catch block is used to.
 Both System.out and System.err are streams—a sequence of bytes.  System.out (the standard output stream) displays output  System.err (the standard.
Exceptions1 Syntax, semantics, and pragmatics. Exceptions2 Syntax, semantics, pragmatics Syntax –How it looks, i.e. how we have to program to satisfy.
Exception Handling 1 CISC6795, Spring Introduction 2 Exception – an indication of a problem that occurs during a program’s execution, for examples:
Error Handling with Exceptions Concepts C and other earlier languages often had multiple error-handling schemes, and these were generally established.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 16: Exception Handling.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
CS 3260 Dennis A. Fairclough Version 1.0
Exceptions Briana B. Morrison CSE 1302C Spring 2010.
Understand Error Handling Software Development Fundamentals LESSON 1.4.
11-Jun-15 Exceptions. 2 Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a.
16-Jun-15 Exceptions. Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a null.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Exceptions. Errors and Exceptions An error is a bug in your program –dividing by zero –going outside the bounds of an array –trying to use a null reference.
Exception Handling An Exception is an indication of a problem that occurs during a program’s execution. Exception handling enables the programmer to create.
Exceptions. 2 Objectives Introduce C# exception handling –library exception types –custom exceptions Describe keywords used for exception handling –try.
 2009 Pearson Education, Inc. All rights reserved Exception Handling Many slides modified by Prof. L. Lilien (even many without explicit message).
 2006 Pearson Education, Inc. All rights reserved Exception Handling.
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.
 2009 Pearson Education, Inc. All rights reserved Exception Handling.
 2006 Pearson Education, Inc. All rights reserved Exception Handling.
Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions.
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 9 : Exception Handling King Fahd University of Petroleum & Minerals College of Computer.
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.
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
CIS 270—Application Development II Chapter 13—Exception Handling.
Chapter 12: Exception Handling
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.
Slides Credit Umair Javed LUMS Web Application Development.
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.
Exceptions Syntax, semantics, and pragmatics Exceptions1.
VB.Net - Exceptions Copyright © Martin Schray
COMP Exception Handling Yi Hong June 10, 2015.
Introduction to Exception Handling and Defensive Programming.
Chapter 14: Exception Handling. Objectives In this chapter, you will: – Learn what an exception is – Learn how to handle exceptions within a program –
Exceptions in Java. Exceptions An exception is an object describing an unusual or erroneous situation Exceptions are thrown by a program, and may be caught.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Exception Handling Programmers must deal with errors and exceptional situations: User input errors Device errors Empty disk space, no memory Component.
Sheet 3 HANDLING EXCEPTIONS Advanced Programming using Java By Nora Alaqeel.
Chapter 15: Exception Handling C++ Programming: Program Design Including Data Structures, Fifth Edition.
Exception Handling in C++. Outline What exceptions are and when to use them Using try, catch and throw to detect, handle and indicate exceptions, respectively.
Copyright © Curt Hill Error Handling in Java Throwing and catching exceptions.
1 Exceptions. 2 Syntax Errors, Runtime Errors, and Logic Errors syntax errors, runtime errors, and logic errors You learned that there are three categories.
CMSC 202 Computer Science II for Majors. CMSC 202UMBC Topics Exceptions Exception handling.
C# Exceptions 1 CNS 3260 C#.NET 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.
Lecture 18B Exception Handling and Richard Gesick.
Exception Handling in C++
Syntax, semantics, and pragmatics
Chapter 14: Exception Handling
Exception Handling and
CNS 3260 C# .NET Software Development
Exception Handling Chapter 9 Edited by JJ.
Programming in C# Lesson 5. Exceptions..
Exception Handling Imran Rashid CTO at ManiWeber Technologies.
Exceptions 10-May-19.
CMSC 202 Exceptions.
Presentation transcript:

Error Handling in.NET Exceptions

Error Handling Old way (Win32 API and COM): MyFunction() { error_1 = doSomething(); if (error_1) display error else { continue processing if (error_2) display error else continue processing }

How is Error Handled in.NET? It uses Exceptions Exception handling enables programmers to remove error-handling code from the “main line” of the program’s execution. Examples: Without exceptions: DivideByZeroNoExceptionHandling.cs With exceptions: DivideByZeroTest.sln

Syntax try { // code that requires common cleanup or // exception-recovery operations } catch (InvalidOperationException) { //code that recovers from an InvalidOperationException // (or any exception type derived from it) } catch (SomeOtherException) { // code that recovers from an SomeOtherException // (or any exception type derived from it) } catch { // code that recovers from any kind of exception // when you catch any exception, you usually re-throw throw; } finally { // code that cleans up any operations started // within the try block. This code ALWAYS executes. }

try block A try block contains code that requires common cleanup or exception-recovery operations. The cleanup code should be put in a single finally block. The exception recovery code should be put in one or more catch blocks. Create one catch block for each kind of type you want to handle. A try block must have at least one catch or finally block.

catch block A catch block contains code to execute in response to an exception. If the code in a try block doesn’t cause an exception to be thrown, the CLR will never execute the code in any of its catch blocks. You may or may not specify a catch type in parantheses after catch : The catch type must be of type System.Exception or a type that derived from System.Exception If there is no catch type specified, that catch block handles any exception. This is equivalent to having a catch block that specifies System.Exception as a catch type. CLR searches for a matching catch type from top to bottom. If CLR cannot find any catch type that matches the exception, CLR continues searching up the callstack to find a catch type.

catch block Once the catch block that matches the exception is found, you have 3 choices: 1. Re-throw the same exception, notifying the higher-up call stack of the exception 2. Throw a different exception, giving richer exception information to code higher-up in the call stack 3. Let the code continue from the bottom of the catch block In choices 1-2, an exception is thrown and code starts looking for a catch block whose type matches the exception thrown In choice 3, the finally block is executed You can also specify a variable name like catch(Exception e) to access information specific to the exception.

finally block The CLR does not completely eliminate memory leaks. Why? Even though GC does automatic memory clean-up, it only cleans up if there are no references kept on the object. Even then there may be a delay until the memory is required. Thus, memory leaks can occur if programmers inadvertently keep references to unwanted objects. C# provides the finally block, which is guaranteed to execute regardless of whether an exception occurs. If the try block executes without throwing, the finally block executes. If the try block throws an exception, the finally block still executes regardless of whether the exception is caught. This makes the finally block ideal to release resources from the corresponding try block. Example: UsingExceptions.cs

finally block Local variables in a try block cannot be accessed in the corresponding finally block, so variables that must be accessed in both should be declared before the try block. Placing the finally block before a catch block is a syntax error. A try block does not require a finally block, sometimes no clean-up is needed. A try block can have no more than one finally block. Avoid putting code that might throw in a finally block. Exception handling will still work but the CLR will not keep the information about the first exception just thrown in the corresponding try block.

using The using statement simplifies writing code in which you obtain a resource. The general form of a using statement is: using ( ExampleObject e = new ExampleObject() ) { e.SomeMethod(); } This using statement code is equivalent to: { ExampleObject e = new ExampleObject(); try { e.SomeMethod(); } finally { if ( e != null ) ( ( IDisposable ) e ).Dispose(); } }

System.Exception In.NET, only objects of class Exception and its derived classes may be thrown and caught. Exceptions thrown in other.NET languages can be caught with the general catch clause. Class Exception is the base class of.NET’s exception class hierarchy. A catch block can use a base-class type to catch a hierarchy of related exceptions. A catch block that specifies a parameter of type Exception can catch all exceptions.

System.Exception Properties Class Exception’s properties are used to formulate error messages indicating a caught exception. Property Message stores the error message associated with an Exception object. Property StackTrace contains a string that represents the method- call stack. When an exception occurs, a programmer might use a different error message or indicate a new exception type. The original exception object is stored in the InnerException property. Other properties: HelpLink specifies the location of a help file that describes the problem. Source specifies the name of the application or object that caused the exception. TargetSite specifies the method where the exception originated.

Common.NET Exceptions The CLR generates SystemException s, derived from class Exception, which can occur at any point during program execution. If a program attempts to access an out-of-range array index, the CLR throws an exception of type IndexOutOfRangeException. Attempting to use a null reference causes a NullReferenceException.

FCL-Defined Exceptions System.Exception System.ApplicationException System.SystemException System.AccessViolationException System.ArgumentException System.ArgumentNullException System.ArgumentOutOfRangeException System.FormatException System.IndexOutOfRangeException System.InvalidCastException System.IO.IOException System.IO.FileNotFoundException System.NotImplementedException System.NullReferenceException System.OutOfMemoryException

Determining Which Exceptions a FCL Method Throws Example: Convert.ToInt32 Search for “ Convert.ToInt32 ” in the Index of the Visual Studio online documentation. Select the document entitled Convert.ToInt32 Method. In the document that describes the method, click the link ToInt32(String). The Exceptions section indicates that method Convert.ToInt32 throws two exception types.

What are Exceptions? They are not an “exceptional event”, a rare event that occurs. They are not just errors. They are specific results returned when a method could not complete its task. Example: when should Transfer throw? public class Account { public void Transfer(Account from, Account to, decimal amount) { … } When the Transfer method detects any of such possible conditions and cannot transfer the money, then it should notify the caller that it failed by throwing an exception.

Choosing the Exception to throw When implementing your own methods, you should throw an exception when the method cannot complete its task. Associating each type of malfunction with an appropriately named exception class improves program clarity. 1. What Exception-derived type are you going to throw? You must select a meaningful type You can select a type defined in FCL that matches your semantics If not, you may need to define your own type Your exception type hierarchy should be shallow and wide: that is, create as few base classes as possible 2. What string message are you going to pass to the exception type’s constructor? If the exception is handled, no one will see this exception message. If the exception is unhandled, then the code will probably log this message and a developer would want to understand what went wrong using this message. So the message should give enough detail as possible. Message does not need to be localized.

User-Defined Exceptions User-defined exception classes should derive directly or indirectly from class Exception of namespace System. Exceptions should be documented so that other developers will know how to handle them. User-defined exceptions should define three constructors: a parameterless constructor a constructor that receives a string argument (the error message) a constructor that receives a string argument and an Exception argument (the error message and the inner exception object)

User-Defined Exception Example SquareRootTest

Do not catch everything! try { // code that might fail… } catch (Exception) { … } How can you write code that can recover from all situations??? A class library should never ever swallow all exceptions. The application should get a chance to handle the exception. You can catch all exceptions only if you are going to process it and re-throw it again.

Benefits of Exceptions The ability to keep cleanup code in a dedicated location and making sure this cleanup code will execute The ability to keep code that deals with exceptional situations in a central place The ability to locate and fix bugs in the code Unified error handling: all.NET Framework classes throw exceptions to handle error cases Old Win32 APIs and COM returns a 32-bit error code. Exceptions include a string description of the problem. Exceptions also include a stack trace that tells you the path application took until the error occurred. You can also put any information you want in a user-defined exception of your own. The caller could ignore the error returned by a Win32 API, now the caller cannot continue with exceptions. If the application cannot handle the exception, CLR can terminate the application.

Exercise Modify your Homework 2 to now handle exceptions thrown by file stream classes Also create new exceptions to be thrown from the ItemsFile class for each method for error cases like: File cannot be opened for some reason New item cannot be added for some reason Item to be deleted is not found in the file