06 - Exceptions

  • Uploaded by: api-19624280
  • 0
  • 0
  • June 2020
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View 06 - Exceptions as PDF for free.

More details

  • Words: 990
  • Pages: 25
Exceptions

Objectives “Unfortunately, errors are a part of life. Some are detected by the compiler, some are detected by the CLR, and the remainder go uncaught. C# and Visual Studio .NET provide many techniques for quickly identifying, dealing with, and eliminating errors. But you have to apply them…”

• • •

Debugging in Visual Studio Exception handling in C# Application design

Microsoft

2

Part 1 •

Debugging in Visual Studio…

Microsoft

3

Debugging in Visual Studio •

Two main approaches: – print debugging – source-level debugger available in IDE

• •

The former is understood by all The latter is MUCH more powerful

Microsoft

4

Print debugging • •

From a compiled application: – Console.WriteLine or MessageBox.Show If you are running inside Visual Studio: – System.Diagnostics.Debug.WriteLine prints to Output window

Microsoft

5

Source-level debugger •

Many powerful features: – pause program at any point – step-by-step execution – view the contents of variables, objects, data structures – show call stack – etc.



How to use? 1. set a breakpoint to pause program (i.e. to enter "Break" mode) 2. see Debug menu

Microsoft

6

Setting breakpoints • Easiest way is to click in left margin of source code

• Other options: – see Debug >> New Breakpoint… – you can break when data changes, or under a condition, or … Microsoft

7

Debug menu •

• •

Step-by-step execution – step into – step over – step out of View locals Immediate window

Microsoft

8

Debugging vs. Exception Handling •

Debugging is reactive – it helps you identify and fix errors after the fact – i.e. program has crashed, will crash, or yields incorrect results



Exception handling is proactive – based on the idea that some errors can be recovered from – i.e. program catches error, fixes problem, and keeps running

Microsoft

9

Part 2 •

Exception handling in C#…

Microsoft

10

Exceptions •

A signal that an exceptional condition has occurred



Examples: – divide-by-zero – arithmetic overflow – array access out of bounds – null object reference – file not found – database server unreachable

Microsoft

11

Exceptions in .NET • •



Exceptions are unchecked – i.e. you are not required to document as in Java Exceptions are represented by objects – error codes are "old-fashioned" :-) Different exceptions are denoted by different classes in FCL: System.Exception

System.SystemException

system-defined exceptions

Microsoft

System.ApplicationException

user-defined exceptions 12

Exception propagation •

What happens if an exception occurs? – object propagates up the call chain, looking for code to handle it – if no such code is found, CLR prints msg & terminates app

call sequence

CLR

Main()

One()

Two()

Three()

exception thrown in Three, call stack is unwound in search for handler… Microsoft

13

Example • Example of an unhandled exception: – we try to open a file, but it can't be found… System.IO.FileStream file; file = new System.IO.FileStream("C:\\readme.txt", System.IO.FileMode.Open, System.IO.FileAccess.Read);

Microsoft

14

Exception handling in C# •

The basic mechanism is try-catch – try to perform one or more tasks – catch any exceptions that might occur try { // to perform one or more tasks, which might raise an exception… } catch(Exception ex) {

exception

// if anything goes wrong, we end up down here to handle it… }

Microsoft

15

Example revisted •

Let's repeat previous example of trying to open a file… try { System.IO.FileStream file; file = new System.IO.FileStream("C:\\readme.txt", System.IO.FileMode.Open, System.IO.FileAccess.Read); . . . file.Close(); }

catch(Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); System.Diagnostics.Debug.WriteLine(ex.StackTrace);

MessageBox.Show("Error: " + ex.Message); }

Microsoft

16

Semantics of try-catch •

Control flows in one of two ways: – no exception occurs: we skip over Catch block – exception occurs: control transfers immediately to Catch no exception

statement1 fails

try { statement1 statement2 statement3 } catch(Exception ex) { statement4 statement5 } statement6 Microsoft

17

Altering the default control flow •

After catching an exception, you might: – consider exception handled & return to caller – rethrow exception if you were unable to handle it – exit application try { . . . } catch(Exception ex) { throw ex; // rethrow exception to caller }

Microsoft

18

Part 3 •

Application design…

Microsoft

19

Cleanup • •

To ensure proper cleanup, use try-catch-finally pattern Finally block is guaranteed to run after you exit try or catch… System.IO.FileStream

file = null;

try { file = new System.IO.FileStream("C:\\readme.txt", System.IO.FileMode.Open, System.IO.FileAccess.Read); . . . }

catch(Exception ex) { throw ex; } finally { // ensure file is closed if (file != null) file.Close(); } Microsoft

20

General exception handling • •

Many different kinds of exceptions can occur Exception kind is determined by object type – use multiple catch blocks, which are applied top-down… try { . . . } catch(System.IO.FileNotFoundException ex) { ... } catch(System.ArithmeticException ex) { ... } catch(Exception ex) { // generic catch-all ... }

Microsoft

21

Class design •

Classes should throw exceptions to signal errors… – classes should not attempt to communicate with user (that's the job of the GUI)

public class Employee { . . .

public decimal Salary // salary property… { get { return this.m_Salary; } set { if (value < 0.0M) // invalid salary value! throw new ApplicationException("Invalid Salary!"); else this.m_Salary = value; } }

Microsoft

22

App design •

At the very least, application should catch and inform user – easily done within Main method… public static void Main() { try { // to run GUI app… Application.Run( new Form1() ); } catch(Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); System.Diagnostics.Debug.WriteLine(ex.StackTrace); MessageBox.Show("Halting due to error: " + ex.Message);

} }

Microsoft

23

Summary • •

Unfortunately, errors are a part of programming Some you can recover from, some you cannot



C# offers reasonable support for exception handling – on par with other programming languages



Beware! – more subtle than it looks – requires significant effort – don't forget to test! – necessary as computers pervade our lives…

Microsoft

24

Lab? •

Work on lab, "OOP and Exceptions"…

Microsoft

25

Related Documents

06 - Exceptions
June 2020 14
Exceptions
November 2019 24
Exceptions
May 2020 19
Perl-exceptions
May 2020 16
Exceptions Ch10
November 2019 23
Exceptions In Java
August 2019 39