Exceptions Programming in C# Exceptions CSE 494R (proposed course for 459 Programming in C#) Prof. Roger Crawfis.

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

Error Handling in.NET Exceptions. Error Handling Old way (Win32 API and COM): MyFunction() { error_1 = doSomething(); if (error_1) display error else.
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.
COMP 121 Week 5: Exceptions and Exception Handling.
CSE 332: C++ exceptions Overview of C++ Exceptions Normal program control flow is halted –At the point where an exception is thrown The program call stack.
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.
Exceptions and Exception Handling Carl Alphonce CSE116 March 9, 2007.
Exception Handling Yaodong Bi Exception Handling Java exception handling Try blocks Throwing and re-throwing an exception Catching an.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 10 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology/ George Koutsogiannakis 1.
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.
Copyright © 2012 Pearson Education, Inc. Chapter 8 Exception Handling.
CS 3260 Dennis A. Fairclough Version 1.0
Exceptions Briana B. Morrison CSE 1302C Spring 2010.
Microsoft VB 2005: Reloaded, Advanced Chapter 5 Input Validation, Error Handling, and Exception Handling.
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.
Slides prepared by Rose Williams, Binghamton University Chapter 9 More 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.
CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Ganesh Viswanathan Exception Handling in Java Course Lecture Slides 7 th July 2010 “ Admitting.
June 14, 2001Exception Handling in Java1 Richard S. Huntrods June 14, 2001 University of Calgary.
1 Exceptions and error handling. 2 Java exception mechanism when an error or exceptional condition occurs, you throw an exception which is caught by an.
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
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.
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
Advanced C# Eric Gunnerson Program Manager Visual C#.NET Microsoft Corporation.
Effective.NET Framework based Development: Exception Handing and Memory Management Effective.NET Framework based Development: Exception Handing and Memory.
Introduction to Exception Handling and Defensive Programming.
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.
Sheet 3 HANDLING EXCEPTIONS Advanced Programming using Java By Nora Alaqeel.
Exceptions and Assertions Chapter 15 – CSCI 1302.
CSE 332: C++ Statements C++ Statements In C++ statements are basic units of execution –Each ends with ; (can use expressions to compute values) –Statements.
Exception Handling in Java Topics: Introduction Errors and Error handling Exceptions Types of Exceptions Coding Exceptions Summary.
Exceptions in Java. What is an exception? An exception is an error condition that changes the normal flow of control in a program Exceptions in Java separates.
1 Exceptions. 2 Syntax Errors, Runtime Errors, and Logic Errors syntax errors, runtime errors, and logic errors You learned that there are three categories.
(c) University of Washington10-1 CSC 143 Java Errors and Exceptions Reading: Ch. 15.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
Exception Handling How to handle the runtime errors.
C# Exceptions 1 CNS 3260 C#.NET Software Development.
ECE122 L23: Exceptions December 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions.
Introduction to Exceptions in Java CS201, SW Development Methods.
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.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
Lecture 11 Dr. Eng. Ibrahim El-Nahry Exception Handling.
Syntax, semantics, and pragmatics
Creating and Modifying Text part 2
Exceptions 10-Nov-18.
CNS 3260 C# .NET Software Development
Exception Handling Chapter 9.
Exception Handling Chapter 9 Edited by JJ.
Exception Handling.
Part B – Structured Exception Handling
Exception Handling Imran Rashid CTO at ManiWeber Technologies.
Exceptions 19-Feb-19.
Exceptions 25-Apr-19.
Exceptions 22-Apr-19.
Exceptions 10-May-19.
Exceptions 5-Jul-19.
Presentation transcript:

Exceptions Programming in C# Exceptions CSE 494R (proposed course for 459 Programming in C#) Prof. Roger Crawfis

Slides are not finished Not sure we will cover this topic.

Exceptional Situations Sometimes, runtime errors are caused by unusual situations, not programming errors For example: writing data to a file Most of the time things go uneventfully, but... The disk may be full There may be a hardware error The file may have been changed to read-only Fragile code ignores the possibility of problems Robust code anticipates such problems

The Traditional Method I Traditional way of handling is to use "completion codes" GET A FILENAME OPEN THE FILE IF THERE IS NO ERROR OPENING THE FILE READ SOME DATA IF THERE IS NO ERROR READING THE DATA PROCESS THE DATA WRITE THE DATA IF THERE IS NO ERROR WRITING THE DATA CLOSE THE FILE IF THERE IS NO ERROR CLOSING FILE RETURN

The Traditional Method II Things to notice with completion codes Almost every step may fail, except "PROCESS DATA" Program just be prepared to deal with failure Very difficult to determine "normal" actions So concerned with things that can go wrong that it is hard to tell if you are doing the right things in the right order Difficult to use if library function contains such code Function must return several error codes so that user can tell what went wrong

The Exceptional Method Using exceptions the code looks like this TRY TO DO THESE THINGS: GET A FILENAME OPEN THE FILE READ SOME DATA PROCESS THE DATA WRITE THE DATA CLOSE THE FILE RETURN IF ERROR OPENING THE FILE THEN... IF ERROR READING THE DATA THEN... IF ERROR WRITING THE DATA THEN... IF ERROR CLOSING THE FILE THEN...

Exception Advantages Compare methods of handling "bad things" Code that uses the exception strategy: Is shorter and easier to read Makes the normal logic the main focus of the method. In the completion code version, the error-handling code obscures the normal actions Allows you to decide whether to handle the problem or defer handling the error on a case-by-case basis Ideal for library-based code

Exception Objects In C#, when a runtime error occurs Exception The CLR sees the problem and creates an Exception System.Exception Object is from a subclass of System.Exception ApplicationException Class ApplicationException : extend & recover SystemException Class SystemException : fix by proper coding The exception object is thrown back up the call stack until a method is found that wants to catch it If it is not "caught" then the CLR runtime system prints an error message

Following Exceptions CLR Runtime The Main( ) method First Method Exception Thrown Here Method Calls Travel Down Exceptions Passed Up

Using try-catch try- catch In C#, you handle exceptions with try- catch try Put the code that may cause an exceptional situation into a “ try ” block. catch try Provide one or more “ catch ” blocks immediately following the “ try ” block catch You should provide catch blocks for all errors you want to handle. Do this by choosing to catch particular classes. catch If you don’t provide a catch block for a particular exception, then the exception will be propagated up

The try-catch Syntax

The try block try The try block consists of: try The keyword try Followed by a brace-delimited block Braces are required: part of the syntax if This is unlike loops and if statements try Inside the try block Place any number of statements that may throw an exception

The catch Block try Place one or more immediately following try Nothing but whitespace or comments between catch Syntax for catch block is a little tricky catch (Exception-Class [var1]) { // Handle exception 1 here } catch (Exception-Class [var2]) { // Handle exception 2 here }

A try-catch Example Example : DivideByZeroTest.csDivideByZeroTest.cs Find on Q: drive in folder ch11\Fig11_01 Drag and drop on F: or U: drive Convert.ToInt32() Method Convert.ToInt32() will automatically detect for invalid representation of an integer FormatException Method generates a FormatException CLR automatic detection for division by zero DivideByZeroException Occurrence will cause a DivideByZeroException

Now, Finally, finally When an exception is thrown catch Control jumps to the catch block that handles it Code that releases resources may be skipped Open File Read Data // Exception thrown here Close File // This is skipped. File still open try-catchfinally The try-catch has an optional finally part This will always be called Use to handle resource depletion

Throwing Exceptions try-catch-finally You aren't restricted to try-catch-finally You can throw exceptions as well Exception Must be an Exception object or a subclass if (numerator == 0) throw new Exception("Illegal numerator"); You can rethrow a caught exception as well Example: Figure 11-2, UsingExceptions.cs UsingExceptions.cs

Exception Object Properties Properties for a caught exception [ Properties.cs ] Properties.cs Message Message : error message associated with an exception May be a default message or customized StackTrace StackTrace : string representing the method call stack List of "pending" methods when the exception occurred The exact location is called the throw point InnerException InnerException property “Wrap” exception objects caught in code Then throw new exception types

Defining Your Own Exceptions Your program may have "application- specific" exceptions To define your own exception classes ApplicationException Derive a new class from ApplicationException For consistencies sake, name should end with “Exception” Should define three constructors A default constructor A constructor that receives a string argument A constructor that takes a string and an Exception argument Example: NegativeNumberException.csNegativeNumberException.cs

Handling Integer Overflow Traditionally, integer overflow is not a runtime error If a result is too large the answer is silently truncated int ans = * / ; C# allows you to change this on a calc- by-calc basis int ans = checked( * / ); OverflowException Throws an OverflowException unchecked() There is a matching unchecked() operator Example: Overflow.csOverflow.cs

Exceptions in C# Must inherit from System.Exception Standard error handling in C# Are thrown when: the code reaches a throw statement System exceptions occur (such as divide by zero) No checked exceptions or exception specifications

Creating an Exception Class Inherit ultimately from System.Exception public class Exception1 : System.Exception { public Exception1(string message) : base(message){} } public class SomeException : Exception1 { public SomeException(string message) : base(message){} }

throw statement Must throw an instance of an exception: throw(new MyException(“Error”)); May be used by itself only in a catch block: catch { throw; }

Catching an Exception A catch block is associated with a try block A try block may have more than one catch block catch blocks catch the exception type or any derived exception types passing through catch blocks are searched in the order they appear in the code catch blocks for specific types must come before the more general types An Empty catch clause will catch any type catch clauses don’t need a variable name catch(Exception) is ok

catch blocks void function1() { try { // code } catch(Exception1 ex) { } catch(Exception ex) { } // if no rethrow occurs // execution resumes here } void function1() { try { // code } catch(Exception ex) { } catch(Exception1 ex) { } } Wrong Right

Exception Flow Control void function1() { try { try { throw(new SomeOtherException(“Error Message”)); } catch(Exception1 ex) { } catch(Exception2 ex) { } } The exception is passed up the call-stack until a suitable handler is found

Exception Flow Control void function2() { try { Function1(); } catch(Exception3 ex3) { } catch(Exception2 ex4) { } catch(Exception ex) { } } If no suitable handler (catch clause) was found, the exception is passed to the calling method

Unhandled Exceptions If no error handler is found the application terminates Control is passed back to Windows

finally block Must be associated with a try block a try block may have only one finally block finally block always gets executed The appropriate catch clause is executed first

finally Flow Control void function1() { try { try { throw(new SomeException(“Error Message”)); } catch(Exception1 ex) { } finally { } catch(Exception2 ex) { } finally { }

Some Special Rules Unhandled Exception in a destructor destructor stops executing, exception is discarded, base destructor is called catch (with no parameter) will catch unmanaged exceptions from other languages

Library Exceptions Feel free to use these: ArithmeticException ArrayTypeMismatchException DivideByZeroException IndexOutOfRangeException InvalidCastException NullReferenceException OutOfMemoryException OverflowException StackOverflowException TypeInitializationException

System.Exception Class Message string message associated with the exception InnerException If this exception was generated inside an exception handler, this refers to the original exception Source Refers to the source class StackTrace String representing the call stack, file and line number

Breaking On Exceptions Debug | Exceptions (or Ctrl + D, E)

Exception Handling Provides tremendous benefits Requires a different way of thinking

The old way RETVAL Process(int a, int x, int y, int z) { RETVAL retval; if ((retval = function(x, y, z)) != OK) return retval; if ((retval = function2(a, y)) != OK) return retval; }

Option 1 void Process(int a, int x, int y, int z) { try { function(x, y, z); } catch (Exception e) { throw e; } try { function2(a, y); } catch (Exception e) { throw e; }

Option 2 void Process(int a, int x, int y, int z) { try { function(x, y, z); function2(a, y); } catch (Exception e) { throw e; }

Option 3 void Process(int a, int x, int y, int z) { function(x, y, z); function2(a, y); }

Exception Handling You get correct behavior by default Only catch an exception when you can do something useful for the user You can write lots of unnecessary code, but at least your code will be less robust

When to catch Something specific happens, and we can help try{ StreamReader s = File.OpenText(filename); StreamReader s = File.OpenText(filename);} catch (Exception e) { Console.WriteLine(“Invalid filename: {0}”, filename); Console.WriteLine(“Invalid filename: {0}”, filename);}try{ StreamReader s = File.OpenText(filename); StreamReader s = File.OpenText(filename);} catch (FileNotFoundException e) { Console.WriteLine(e); Console.WriteLine(e);}

try{ ExecuteBigProcess(); ExecuteBigProcess();} catch (Exception e) { log.WriteLine(e.ToString()); log.WriteLine(e.ToString()); throw; throw;}try{ ExecuteBigProcess(); ExecuteBigProcess();} catch (Exception e) { throw new MyException(“Error executing BigProcess”, e); throw new MyException(“Error executing BigProcess”, e);} When to catch We need to log or wrap an exception

When to catch Process would die otherwise public static void Main() { while (true) while (true) { try try { MainLoop(); MainLoop(); } catch (Exception e) catch (Exception e) { Console.WriteLine(“Exception caught, trying to continue”); Console.WriteLine(“Exception caught, trying to continue”); Console.WriteLine(e); Console.WriteLine(e); } }}

Finally statement If an exception is thrown and There’s something to clean up Close a file Release a DB handle Using statement makes this easier Works on anything that implements IDisposable

Using Statement Acquire, Execute, Release pattern Works with any IDisposable object Data access classes, streams, text readers and writers, network classes, etc. using (Resource res = new Resource()) { res.DoWork(); res.DoWork();} Resource res = new Resource(...); try { res.DoWork(); res.DoWork();} finally { if (res != null) ((IDisposable)res).Dispose(); if (res != null) ((IDisposable)res).Dispose();}

Using Statement static void Copy(string sourceName, string destName) { Stream input = File.OpenRead(sourceName); Stream input = File.OpenRead(sourceName); Stream output = File.Create(destName); Stream output = File.Create(destName); byte[] b = new byte[65536]; byte[] b = new byte[65536]; int n; int n; while ((n = input.Read(b, 0, b.Length)) != 0) { while ((n = input.Read(b, 0, b.Length)) != 0) { output.Write(b, 0, n); output.Write(b, 0, n); } output.Close(); output.Close(); input.Close(); input.Close();} static void Copy(string sourceName, string destName) { Stream input = File.OpenRead(sourceName); Stream input = File.OpenRead(sourceName); try { try { Stream output = File.Create(destName); Stream output = File.Create(destName); try { try { byte[] b = new byte[65536]; byte[] b = new byte[65536]; int n; int n; while ((n = input.Read(b, 0, b.Length)) != 0) { while ((n = input.Read(b, 0, b.Length)) != 0) { output.Write(b, 0, n); output.Write(b, 0, n); } } finally { finally { output.Close(); output.Close(); } } finally { finally { input.Close(); input.Close(); }} static void Copy(string sourceName, string destName) { using (Stream input = File.OpenRead(sourceName)) using (Stream input = File.OpenRead(sourceName)) using (Stream output = File.Create(destName)) { using (Stream output = File.Create(destName)) { byte[] b = new byte[65536]; byte[] b = new byte[65536]; int n; int n; while ((n = input.Read(b, 0, b.Length)) != 0) { while ((n = input.Read(b, 0, b.Length)) != 0) { output.Write(b, 0, n); output.Write(b, 0, n); } }}

Exceptions vs Return Codes Exceptions are meant for exceptional cases Invalid parameters Can’t perform operation Should not occur during normal program operation User interaction is a grey area

Using Return Values Okay if your caller always will have to check and recover from something Make sure you don’t force them to write: Shouldn’t be possible to do the wrong thing File.Open() returns null on file not found You can’t ignore this bool success = TryOperation(param1, param2); if (!success) return success; return success;

Summary Understand how the model works Don’t work too hard If you can’t do something useful, don’t catch

Exceptions Programming in C# Exceptions CSE 494R (proposed course for 459 Programming in C#) Prof. Roger Crawfis

XML Documentation Programming in C# XML Documentation CSE 494R (proposed course for 459 Programming in C#) Prof. Roger Crawfis

XML Documentation Programming in C# XML Documentation CSE 494R (proposed course for 459 Programming in C#) Prof. Roger Crawfis