10/20/2015Assoc. Prof. Stoyan Bonev1 COS240 O-O Languages AUBG, COS dept Lecture 37 Title: C# vs....

67
03/22/22 Assoc. Prof. Stoyan Bonev 1 COS240 O-O Languages AUBG, COS dept Lecture 37 Title: C# vs. Java Exception Handling Reference: COS240 Syllabus

Transcript of 10/20/2015Assoc. Prof. Stoyan Bonev1 COS240 O-O Languages AUBG, COS dept Lecture 37 Title: C# vs....

04/20/23 Assoc. Prof. Stoyan Bonev 1

COS240 O-O Languages AUBG, COS dept

Lecture 37Title:

C# vs. Java Exception Handling

Reference: COS240 Syllabus

04/20/23 Assoc. Prof. Stoyan Bonev 2

Lecture Contents:

• Errors, Bugs, Exceptions

• EH Techniques

• Exception Classes

• Sample demo programs

C# Programming: From Problem Analysis to Program Design 3C# Programming: From Problem Analysis to Program Design 3

Debugging and Handling Exceptions

C# Programming: From Problem Analysis to Program Design 3rd Edition

12

C# Programming: From Problem Analysis to Program Design 4C# Programming: From Problem Analysis to Program Design 4

Errors

• Visual Studio IDE reports errors as soon as it is able to detect a problem

• Compile-time /Syntax/ errors– Language rule violation

• Run-time errors– Incorrect program execution

C# Programming: From Problem Analysis to Program Design 5C# Programming: From Problem Analysis to Program Design 5

Run-Time Errors

• Just because your program reports no syntax errors does not necessarily mean it is running correctly

• Sometimes program stops during execution.• Other times, output is produced, but the output

might not be correct.• Sometimes program works properly with some

data, but crash when a certain value is entered.

C# Programming: From Problem Analysis to Program Design 6C# Programming: From Problem Analysis to Program Design 6

Exceptions • Even if you are perfect developer, take care:• Errors do occur at run time• A primitive action to keep your programs from

crashing is to include if stmts in order:– To Check values used as input to ensure the value is numeric

prior to parsing/converting the string into numeric equivalent. – To Test numeric values for valid range prior to use in

arithmetic– To Test candidates for divisors to be not zero valued– To Test subscript/index values used with arrays to make sure

they are valid– To Test input controls like text boxes for empty string input– To Test file existance prior to try reading data from a file

C# Programming: From Problem Analysis to Program Design 7C# Programming: From Problem Analysis to Program Design 7

Exceptions • Unless provisions are made for handling exceptions,

your program may crash or produce erroneous results– Unhandled exception

• Message displayed when you are creating console application and unhandled exception occurs

C# Programming: From Problem Analysis to Program Design 8C# Programming: From Problem Analysis to Program Design 8

Raising an Exception • Error encountered – no recovery

– If a program encounters an error, and the program cannot recover from the error, the program Raises/Throws/ an Exception

– Execution halts in the current method and the Common Language Runtime (CLR) attempts to locate an exception handler

• Exception handler: block of code to be executed when a certain type of error occurs

• See next page IMPORTANT NOTES

C# Programming: From Problem Analysis to Program Design 9C# Programming: From Problem Analysis to Program Design 9

Raising an Exception

Next slide

of

High Importance

C# Programming: From Problem Analysis to Program Design 10C# Programming: From Problem Analysis to Program Design 10

Raising an Exception IMPORTANT NOTES:

– If CLR finds an Exception Handler in the current method, control is transferred to that code

– If no exception handler is found in current method, that method is halted, and exception is thrown back to the parent calling method in order the parent method to handle the exception

– If more than two methods are used, the exception continues to be thrown back to the calling method until it reaches the top most method

– If none of the methods includes code to handle the error, CLR handles the exception by halting the application.

– If CLR handles an exception by halting a program, that exception is called an unhandled exception.

C# Programming: From Problem Analysis to Program Design 11C# Programming: From Problem Analysis to Program Design 11

Bugs, Errors, and Exceptions• Bugs differ from exceptions

– Bugs, also called "programmer mistakes," should be caught and fixed before application released

• Errors can be created because of user actions. These actions can cause exceptions to be thrown

• Example – Entering wrong type of data produces unhandled

exception when Parse( ) method or methods in the Convert class is executed with non numeric data.

C# Programming: From Problem Analysis to Program Design 12C# Programming: From Problem Analysis to Program Design 12

Exception-Handling Techniques• If event creates a problem frequently, best to use

conditional expressions to catch and fix problem

– Execution is slowed down when CLR has to halt a method and find an appropriate event handler

• Exception-handling techniques are for serious errors that occur infrequently

• Exceptions classes integrated within the FCL

– Used with the try … catch … finally program constructs

C# Programming: From Problem Analysis to Program Design 13C# Programming: From Problem Analysis to Program Design 13

C#, like C++, Java handles exceptions through Try…Catch…Finally Blocks

• Code that may create a problem is placed in the try block

• Code to deal with the problem (the exception handler) is placed in catch blocks

– Catch clause

• Code to be executed whether an exception is thrown or not, is placed in the finally block

C# Programming: From Problem Analysis to Program Design 14C# Programming: From Problem Analysis to Program Design 14

try

{

// Statements

}

catch [ (ExceptionClassName exceptionIdentifier) ]

{

// Exception handler statements

}

[additional catch clauses]

[ finally

{

// Statements

} ]

Notice square brackets indicate

optional entry

One catch clause required

finally clause optional

C# Programming: From Problem Analysis to Program Design 15C# Programming: From Problem Analysis to Program Design 15

Try…Catch…Finally Blocks (continued)

• Generic catch clause– Omit argument list with the catch

– Any exception thrown is handled by executing code within that catch block

• Control is never returned into the try block after an exception is thrown

• Using a try…catch block can keep the program from terminating abnormally

C# Programming: From Problem Analysis to Program Design 16C# Programming: From Problem Analysis to Program Design 16

Use of Generic Catch Clause

Figure 12-14 Generic catch block handles the exception

Example 11-2uses a generic catch block

C# Programming: From Problem Analysis to Program Design 17C# Programming: From Problem Analysis to Program Design 17

What Caused These Exceptions to be Thrown?

Never quite sure what causes theexception to be thrown when a generic catch clause is used!

Figure 12-15 Exceptions – division by zero and programmer errors

C# Programming: From Problem Analysis to Program Design 18C# Programming: From Problem Analysis to Program Design 18

Exception Object• When an exception is raised, an object is created

– Object has properties and behaviors (methods)

• Catch clause may list an exception class

– Catch { } without exception type does not give you access to an object

• Base exception class: Exception

– Message property returns a string describing exception

– StackTrace property returns a string that contains the called trace of methods

C# Programming: From Problem Analysis to Program Design 19C# Programming: From Problem Analysis to Program Design 19

Exception Object (continued)catch (System.Exception e) { Console.Error.WriteLine("Problem with scores - " + "Can not compute average"); Console.Error.WriteLine(e.Message);}

Figure 12-16 Use of Message property with the exception object

C# Programming: From Problem Analysis to Program Design 20C# Programming: From Problem Analysis to Program Design 20

Exception Classes

• When an error occurs, it is reported by creating and throwing an object that corresponds to the specific type of exception that is thrown.

• The object contains information about the error.• There are a huge number of different exceptions

that can be thrown. Hierarchy of classes and top level is the Exception class.

• See next slide for a partial list of Derived Classes of the Base Exception class

C# Programming: From Problem Analysis to Program Design 21C# Programming: From Problem Analysis to Program Design 21

Exception Classes

• The two exception classes of interest are the ApplicationException and SystemException classes. They form the basis for run-time exceptions

C# Programming: From Problem Analysis to Program Design 22C# Programming: From Problem Analysis to Program Design 22

Exception Classes (continued)• ApplicationException

– Derive from this class when you write your own exception classes

– User program must throw the exception, not the CLR

C# Programming: From Problem Analysis to Program Design 23C# Programming: From Problem Analysis to Program Design 23

Exception Classes (continued)• SystemException

– Most run-time exceptions derive from this class

– SystemException class adds no functionality to classes; includes no additional properties or methods

• More than 70 classes derived from SystemException

C# Programming: From Problem Analysis to Program Design 24C# Programming: From Problem Analysis to Program Design 24

SystemException Class

C# Programming: From Problem Analysis to Program Design 25C# Programming: From Problem Analysis to Program Design 25

System.DivideByZeroException• Derived class of System.ArithmeticException

class

• Thrown when an attempt to divide by zero occurs

• Only thrown for integral or integer data types

• Floating-point operands do not throw an exception

– Result reported as either positive infinity, negative infinity, or Not-a-Number (NaN)

– Follows the rules from IEEE 754 arithmetic

C# Programming: From Problem Analysis to Program Design 26C# Programming: From Problem Analysis to Program Design 26

Filtering Multiple Exceptions

• Can include multiple catch clauses

• Enables writing code specific to thrown exception

• Should be placed from most specific to the most generic

• If Exception class is included, it should always be placed last

C# Programming: From Problem Analysis to Program Design 27C# Programming: From Problem Analysis to Program Design 27

Custom Exceptions

• Derive from the ApplicationException class

• Good idea to use the word “Exception” as part of the identifier

• Creating an exception class is no different from creating any other class

C# Programming: From Problem Analysis to Program Design 28C# Programming: From Problem Analysis to Program Design 28

Custom Exceptions (continued)

public class FloatingPtDivisionException : System.ApplicationException

{ public FloatingPtDivisionException

(string exceptionType) : base (exceptionType)

{ // Empty body

}}

String argument sent to the baseconstructor indicating type of exception

C# Programming: From Problem Analysis to Program Design 29C# Programming: From Problem Analysis to Program Design 29

public class TestOfCustomException{

static void Main(string[] args){

double value1 = 0, value2=0, answer;try{ //Could include code to enter new values.

answer = GetResults(value1, value2);}catch (FloatingPtDivisionException excepObj){

Console.Error.WriteLine(excepObj.Message);}catch{

Console.Error.WriteLine(“Something else happened!”);}

}

User-defined

class

C# Programming: From Problem Analysis to Program Design 30C# Programming: From Problem Analysis to Program Design 30

Custom Exceptions (continued)

• Throwing a programmer-defined exception

– Exception object is instantiated when “an exceptional condition occurs”

– Can be any condition, but should be one that happens infrequently

– After object is instantiated, object is thrown

C# Programming: From Problem Analysis to Program Design 31C# Programming: From Problem Analysis to Program Design 31

static double GetResults (double value1, double value2){

if (value2 < .0000001) // Be careful comparing floating- // point values for equality.

{FloatingPtDivisionException excepObj = new

FloatingPtDivisionException(“Exception type: “ +“Floating-point division by zero”);

throw excepObj;}return value1 / value2;}

}

Throwing an exception

C# Programming: From Problem Analysis to Program Design 32C# Programming: From Problem Analysis to Program Design 32

Input Output (IO) Exceptions • System.IO.IOException

– Direct descendent of Exception

– Thrown when a specified file or directory is not found

– Thrown when program attempts to read beyond the end of a file

– Thrown when there are problems loading or accessing the contents of a file

C# Programming: From Problem Analysis to Program Design 33C# Programming: From Problem Analysis to Program Design 33

Input Output (IO) Exceptions (continued)

C# Programming: From Problem Analysis to Program Design 34

Coding Standards

• Avoid using exception-handling techniques to deal with problems that can be handled with reasonable coding effort

• Encapsulating all methods in a try...catch block hampers performance

• Order exceptions from the most specific to the least specific

• Add Exception onto the end of the name for custom classes

C# Programming: From Problem Analysis to Program Design 34

04/20/23 Assoc. Prof. Stoyan Bonev 35

Assoc. Prof. Stoyan Bonev04/20/23 36

EH from Java to C#

To demonstrate EH, including how an exception object is created and thrown:

Open Quotient.java that reads two integers and displays their quotient.

Unhandled exception demonstrated. No try…catch construct No if stmt to test divisor to be zero

Assoc. Prof. Stoyan Bonev04/20/23 37

EH from Java to C#

Convert – Quotient.java– to– Quotient.cs

Assoc. Prof. Stoyan Bonev04/20/23 38

EH from Java to C#

Simple way to fix the problem is to add if stmt to test the divisor:

Open QuotientWithIf.java that reads two integers and displays their quotient.

Explicit user specified if stmt to test for zero valued divisor.

Assoc. Prof. Stoyan Bonev04/20/23 39

EH from Java to C#

Convert – QuotientWithIF.java – to– QuotientWithIF.cs

Assoc. Prof. Stoyan Bonev04/20/23 40

Exception-Handling Overview

To demonstrate EH, including how to create, throw, catch and handle an exception object:

Open QuotientWithExceptionVerLiang.java that reads two integers and displays their quotient.

Try…catch construct included If stmt explicitly raises/throws an exception.

See text in red

Assoc. Prof. Stoyan Bonev04/20/23 41

Exception-Handling Overviewtry { System.out.print("Enter the dividend: "); dividend = console.nextInt();

System.out.print("Enter the divisor: "); divisor = console.nextInt();

if (divisor == 0) throw new ArithmeticException("Divisor cannot be zero ");

quotient = dividend / divisor;

System.out.println(dividend + " / " + divisor + " is = " + quotient);} // end of try

catch (ArithmeticException aeRef) {System.out.println("Exception: integer cannot divide by 0");System.out.println(aeRef.getMessage());aeRef.printStackTrace(); // print call stack}finally {

System.out.println("\n\n Finally block executed");}

Assoc. Prof. Stoyan Bonev04/20/23 42

Exception-Handling Overview

To demonstrate EH, including how to create, throw, catch and handle an exception object:

Open QuotientWithExceptionVerMalik.java that reads two integers and displays their quotient.

Try…catch construct included Exception raised/thrown implicitly No if stmt to explicitly raise/throw an exception. See

text in red

Assoc. Prof. Stoyan Bonev04/20/23 43

Exception-Handling Overviewtry { System.out.print("Enter the dividend: "); dividend = console.nextInt();

System.out.print("Enter the divisor: "); divisor = console.nextInt();

//if (divisor == 0) //throw new ArithmeticException("Divisor cannot be zero ");

quotient = dividend / divisor;

System.out.println(dividend + " / " + divisor + " is = " + quotient);} // end of try

catch (ArithmeticException aeRef) {System.out.println("Exception: integer cannot divide by 0");System.out.println(aeRef.getMessage());aeRef.printStackTrace(); // print call stack}finally {

System.out.println("\n\n Finally block executed");}

Assoc. Prof. Stoyan Bonev04/20/23 44

EH from Java to C#

Run and Test: QuotientWithExceptionBarbara1.cs

Try…catch construct included Exception raised/thrown implicitly 1 catch clause with no parameter, includes a

single statement to display user specified text

Assoc. Prof. Stoyan Bonev04/20/23 45

EH from Java to C# try { Console.Write("Enter the dividend: "); dividend = Convert.ToInt32(Console.ReadLine());

Console.Write("Enter the divisor: "); divisor = Convert.ToInt32(Console.ReadLine());

quotient = dividend / divisor;

Console.WriteLine(dividend + " / " + divisor + " is = " + quotient);

} // end of try catch { Console.Error.WriteLine("Problem with data - cannot compute quotient"); }

Assoc. Prof. Stoyan Bonev04/20/23 46

EH from Java to C#

Run and Test: QuotientWithExceptionBarbara2.cs

Try…catch construct included Exception raised/thrown implicitly 1 catch() clause with parameter, includes 2

statements – more informative for the user

Assoc. Prof. Stoyan Bonev04/20/23 47

EH from Java to C# try { Console.Write("Enter the dividend: "); dividend = Convert.ToInt32(Console.ReadLine());

Console.Write("Enter the divisor: "); divisor = Convert.ToInt32(Console.ReadLine());

quotient = dividend / divisor;

Console.WriteLine(dividend + " / " + divisor + " is = " + quotient);

} // end of try catch (System.Exception e) { Console.Error.WriteLine("Problem with data - cannot compute quotient"); Console.Error.WriteLine(e.Message); }

Assoc. Prof. Stoyan Bonev04/20/23 48

EH from Java to C#

Run and Test: QuotientWithExceptionBarbara2.cs

Try…catch construct included Exception raised/thrown implicitly 1 catch() clause with parameter, includes 3

statements – still more informative for the user

Assoc. Prof. Stoyan Bonev04/20/23 49

EH from Java to C# try { Console.Write("Enter the dividend: "); dividend = Convert.ToInt32(Console.ReadLine());

Console.Write("Enter the divisor: "); divisor = Convert.ToInt32(Console.ReadLine());

quotient = dividend / divisor;

Console.WriteLine(dividend + " / " + divisor + " is = " + quotient);

} // end of try catch (System.Exception e) { Console.Error.WriteLine("Problem with data - cannot compute quotient"); Console.Error.WriteLine(e.Message);

Console.Error.WriteLine(e.StackTrace); }

Assoc. Prof. Stoyan Bonev04/20/23 50

EH from Java to C#

Run and Test: QuotientWithExceptionBarbara3.cs

Try…catch construct included Exception raised/thrown implicitly 3 catch() clauses – to filter multiple exceptions

ordered in a manner so that First - most specific Last – the least specific, i.e the most common

Assoc. Prof. Stoyan Bonev04/20/23 51

EH from Java to C# try { Console.Write("Enter the dividend: "); dividend = Convert.ToInt32(Console.ReadLine());

Console.Write("Enter the divisor: "); divisor = Convert.ToInt32(Console.ReadLine());

quotient = dividend / divisor;

Console.WriteLine(dividend + " / " + divisor + " is = " + quotient);

} // end of try catch (System.DivideByZeroException e) { Console.Error.WriteLine("Problem with data - cannot compute quotient - level 1"); Console.Error.WriteLine(e.Message); } catch (System.ArithmeticException e) { Console.Error.WriteLine("Problem with data - cannot compute quotient - level 2"); Console.Error.WriteLine(e.Message); } catch (System.Exception e) { Console.Error.WriteLine("Problem with data - cannot compute quotient - level 3"); Console.Error.WriteLine(e.Message); }

Assoc. Prof. Stoyan Bonev04/20/23 52

Exception-Handling Advantages

To demonstrate EH advantages:Open QuotientWithMethod.java that reads two integers and displays their quotient.

Now you see the advantages of using exception handling. It enables a method to throw an exception to its caller. Without this capability, a method must handle the exception or terminate the program.

Assoc. Prof. Stoyan Bonev04/20/23 53

EH from Java to C#

Convert – QuotientWithMethod.java– to– QuotientWithMethod.cs

Assoc. Prof. Stoyan Bonev04/20/23 54

EH from Java to C#

Run and Test: QuotientWithMethod.cs

Assoc. Prof. Stoyan Bonev04/20/23 55

EH from Java to C# class Program { static int quotient(int num1, int num2) { return num1 / num2; } static void Main(string[] args) { int dividend, divisor, result ;

try { Console.Write("Enter the dividend: "); dividend = Convert.ToInt32(Console.ReadLine()); Console.Write("Enter the divisor: "); divisor = Convert.ToInt32(Console.ReadLine());

result = quotient(dividend, divisor); Console.WriteLine(dividend + " / " + divisor + " is = " + result); } // end of try catch(System.Exception e) { Console.Error.WriteLine("Problem with data - cannot compute quotient"); Console.Error.WriteLine(e.Message); } } // end of Main } // end of class Program

Assoc. Prof. Stoyan Bonev04/20/23 56

Example: Declaring, Throwing, and Catching Exceptions

Objective: This example demonstrates handling exceptions by modifying the setRadius method in the Circle class. The new setRadius method throws an exception if radius is negative.

Open CircleWithException.java file

Assoc. Prof. Stoyan Bonev04/20/23 57

EH from Java to C#

Convert – CircleWithException.java – to– CircleWithException.cs

Assoc. Prof. Stoyan Bonev04/20/23 58

EH from Java to C#

Run and Test; CircleWithException.cs

Assoc. Prof. Stoyan Bonev04/20/23 59

EH from Java to C#class Circle { private double radius; private static int numberOfObjects = 0;

// constructors public Circle() { radius = (2.0); numberOfObjects++; } public Circle(double par) { setRadius(par); numberOfObjects++; }

// method accessor public double getRadius() { return radius; } public static int getNumberOfObjects(){ return numberOfObjects;}

// methods mutators public void setRadius(double par) //throwsIllegalArgumentException { if (par >= 0.0) radius = par; else throw new ArgumentException("Radius cannot be negative"); }

public double findArea() { return Math.PI * radius * radius; } public double findCircum() { return 2 * Math.PI * radius; } } // end of class Circle

Assoc. Prof. Stoyan Bonev04/20/23 60

EH from Java to C#class Program { static void Main(string[] args) { try { Circle a = new Circle(); Circle aa = new Circle(); Circle b = new Circle(5.0); Circle c = new Circle(-5.0); Circle cc = new Circle(); } catch (ArgumentException ex) { Console.WriteLine("\n-->>" + ex + "\n-->>"); Console.WriteLine("\n\nSB\n-->>" + ex.Message + "\n-->>"); Console.WriteLine("\n\nSBSB\n-->>" + ex.StackTrace + "\n-->>"); } finally { Console.WriteLine("\n\n Finally block executed"); }

Console.WriteLine("\n\n Execution continues ...");

Console.WriteLine("\nNumber of objects created is = " + Circle.getNumberOfObjects());

} // end of Main } // end of class Program

Assoc. Prof. Stoyan Bonev04/20/23 61

Defining Custom Exception Classes Use the exception classes in the API whenever possible.

Define custom exception classes if the predefined classes are not sufficient.

Define custom exception classes by extending Exception or a subclass of Exception.

Open CircleWithUserException.java file

Assoc. Prof. Stoyan Bonev04/20/23 62

EH from Java to C#

Convert – CircleWithUserException.java – to – CircleWithUserException.cs

Assoc. Prof. Stoyan Bonev04/20/23 63

EH from Java to C#

Run and Test: CircleWithUserException.cs

Assoc. Prof. Stoyan Bonev04/20/23 64

EH from Java to C#

// user/custom defined exception class IllegalRadiusException : ApplicationException { private double rad;

public IllegalRadiusException(double radius) // constructor : base("Invalid radius " + radius) { rad = radius; }

public double getRad() { return rad; } }

Assoc. Prof. Stoyan Bonev04/20/23 65

EH from Java to C#class Circle { private double radius; private static int numberOfObjects = 0;

// constructors public Circle() { radius = 2.0; numberOfObjects++; } public Circle(double par) { // throws IllegalRadiusException setRadius(par); numberOfObjects++; }

// method accessor public double getRadius() { return radius; } public static int getNumberOfObjects() { return numberOfObjects; }

// methods mutators public void setRadius(double par) { //throws IllegalRadiusException if (par >= 0.0) radius = par; else throw new IllegalRadiusException(par); }

public double findArea() { return Math.PI * radius * radius; } public double findCircum() { return 2 * Math.PI * radius; } } // end of class Circle

Assoc. Prof. Stoyan Bonev04/20/23 66

EH from Java to C# class Program { static void Main(string[] args) {

try { Circle a = new Circle(88.0); a.setRadius(-22.0); // Circle b = new Circle(5.0); // Circle c = new Circle(-5.0); } catch (IllegalRadiusException ex) { Console.WriteLine("\n-->>\nInvalid radius is " + ex.getRad() + "\n-->>"); } finally { Console.WriteLine("\n\n Finally block executed"); }

Console.WriteLine("\n\n Execution continues ...");

Console.WriteLine("\nNumber of objects created is = " + Circle.getNumberOfObjects()); } // end of Main } // end of class Program

Thank Youfor

Your attention!