Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "10/20/2015Assoc. Prof. Stoyan Bonev1 COS240 O-O Languages AUBG, COS dept Lecture 37 Title: C# vs. Java Exception Handling Reference: COS240 Syllabus."— Presentation transcript:

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

2 10/20/2015Assoc. Prof. Stoyan Bonev2 Lecture Contents: Errors, Bugs, Exceptions EH Techniques Exception Classes Sample demo programs

3 C# Programming: From Problem Analysis to Program Design3 3 Debugging and Handling Exceptions C# Programming: From Problem Analysis to Program Design 3 rd Edition 12

4 C# Programming: From Problem Analysis to Program Design4 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

5 C# Programming: From Problem Analysis to Program Design5 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.

6 C# Programming: From Problem Analysis to Program Design6 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

7 C# Programming: From Problem Analysis to Program Design7 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

8 C# Programming: From Problem Analysis to Program Design8 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

9 C# Programming: From Problem Analysis to Program Design9 9 Raising an Exception Next slide of High Importance

10 C# Programming: From Problem Analysis to Program Design10C# Programming: From Problem Analysis to Program Design10 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.

11 C# Programming: From Problem Analysis to Program Design11C# Programming: From Problem Analysis to Program Design11 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.

12 C# Programming: From Problem Analysis to Program Design12C# Programming: From Problem Analysis to Program Design12 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

13 C# Programming: From Problem Analysis to Program Design13C# Programming: From Problem Analysis to Program Design13 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

14 C# Programming: From Problem Analysis to Program Design14C# Programming: From Problem Analysis to Program Design14 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

15 C# Programming: From Problem Analysis to Program Design15C# Programming: From Problem Analysis to Program Design15 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

16 C# Programming: From Problem Analysis to Program Design16C# Programming: From Problem Analysis to Program Design16 Use of Generic Catch Clause Figure 12-14 Generic catch block handles the exception Example 11-2 uses a generic catch block

17 C# Programming: From Problem Analysis to Program Design17C# Programming: From Problem Analysis to Program Design17 What Caused These Exceptions to be Thrown? Never quite sure what causes the exception to be thrown when a generic catch clause is used! Figure 12-15 Exceptions – division by zero and programmer errors

18 C# Programming: From Problem Analysis to Program Design18C# Programming: From Problem Analysis to Program Design18 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

19 C# Programming: From Problem Analysis to Program Design19C# Programming: From Problem Analysis to Program Design19 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

20 C# Programming: From Problem Analysis to Program Design20C# Programming: From Problem Analysis to Program Design20 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

21 C# Programming: From Problem Analysis to Program Design21C# Programming: From Problem Analysis to Program Design21 Exception Classes The two exception classes of interest are the ApplicationException and SystemException classes. They form the basis for run-time exceptions

22 C# Programming: From Problem Analysis to Program Design22C# Programming: From Problem Analysis to Program Design22 Exception Classes ( continued ) ApplicationException –Derive from this class when you write your own exception classes –User program must throw the exception, not the CLR

23 C# Programming: From Problem Analysis to Program Design23C# Programming: From Problem Analysis to Program Design23 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

24 C# Programming: From Problem Analysis to Program Design24C# Programming: From Problem Analysis to Program Design24 SystemException Class

25 C# Programming: From Problem Analysis to Program Design25C# Programming: From Problem Analysis to Program Design25 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

26 C# Programming: From Problem Analysis to Program Design26C# Programming: From Problem Analysis to Program Design26 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

27 C# Programming: From Problem Analysis to Program Design27C# Programming: From Problem Analysis to Program Design27 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

28 C# Programming: From Problem Analysis to Program Design28C# Programming: From Problem Analysis to Program Design28 Custom Exceptions ( continued ) public class FloatingPtDivisionException : System.ApplicationException { public FloatingPtDivisionException (string exceptionType) : base (exceptionType) { // Empty body } String argument sent to the base constructor indicating type of exception

29 C# Programming: From Problem Analysis to Program Design29C# Programming: From Problem Analysis to Program Design29 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

30 C# Programming: From Problem Analysis to Program Design30C# Programming: From Problem Analysis to Program Design30 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

31 C# Programming: From Problem Analysis to Program Design31C# Programming: From Problem Analysis to Program Design31 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

32 C# Programming: From Problem Analysis to Program Design32C# Programming: From Problem Analysis to Program Design32 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

33 C# Programming: From Problem Analysis to Program Design33C# Programming: From Problem Analysis to Program Design33 Input Output (IO) Exceptions ( continued )

34 C# Programming: From Problem Analysis to Program Design34 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 Design34

35 10/20/2015Assoc. Prof. Stoyan Bonev35

36 Assoc. Prof. Stoyan Bonev 10/20/2015 36 EH from Java to C# F To demonstrate EH, including how an exception object is created and thrown:  Open Quotient.java that reads two integers and displays their quotient. F Unhandled exception demonstrated.  No try…catch construct  No if stmt to test divisor to be zero

37 Assoc. Prof. Stoyan Bonev 10/20/2015 37 EH from Java to C# F Convert – Quotient.java – to – Quotient.cs

38 Assoc. Prof. Stoyan Bonev 10/20/2015 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.

39 Assoc. Prof. Stoyan Bonev 10/20/2015 39 EH from Java to C# F Convert – QuotientWithIF.java – to – QuotientWithIF.cs

40 Assoc. Prof. Stoyan Bonev 10/20/2015 40 Exception-Handling Overview F To demonstrate EH, including how to create, throw, catch and handle an exception object: F 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

41 Assoc. Prof. Stoyan Bonev 10/20/2015 41 Exception-Handling Overview try { 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"); }

42 Assoc. Prof. Stoyan Bonev 10/20/2015 42 Exception-Handling Overview F To demonstrate EH, including how to create, throw, catch and handle an exception object: F Open QuotientWithExceptionVerMalik.java that reads two integers and displays their quotient.  Try…catch construct included F Exception raised/thrown implicitly  No if stmt to explicitly raise/throw an exception. See text in red

43 Assoc. Prof. Stoyan Bonev 10/20/2015 43 Exception-Handling Overview try { 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"); }

44 Assoc. Prof. Stoyan Bonev 10/20/2015 44 EH from Java to C#  Run and Test: QuotientWithExceptionBarbara1.cs  Try…catch construct included F Exception raised/thrown implicitly F 1 catch clause with no parameter, includes a single statement to display user specified text

45 Assoc. Prof. Stoyan Bonev 10/20/2015 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"); }

46 Assoc. Prof. Stoyan Bonev 10/20/2015 46 EH from Java to C#  Run and Test: QuotientWithExceptionBarbara2.cs  Try…catch construct included F Exception raised/thrown implicitly F 1 catch() clause with parameter, includes 2 statements – more informative for the user

47 Assoc. Prof. Stoyan Bonev 10/20/2015 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); }

48 Assoc. Prof. Stoyan Bonev 10/20/2015 48 EH from Java to C#  Run and Test: QuotientWithExceptionBarbara2.cs  Try…catch construct included F Exception raised/thrown implicitly F 1 catch() clause with parameter, includes 3 statements – still more informative for the user

49 Assoc. Prof. Stoyan Bonev 10/20/2015 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); }

50 Assoc. Prof. Stoyan Bonev 10/20/2015 50 EH from Java to C#  Run and Test: QuotientWithExceptionBarbara3.cs  Try…catch construct included F Exception raised/thrown implicitly F 3 catch() clauses – to filter multiple exceptions ordered in a manner so that F First - most specific F Last – the least specific, i.e the most common

51 Assoc. Prof. Stoyan Bonev 10/20/2015 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); }

52 Assoc. Prof. Stoyan Bonev 10/20/2015 52 Exception-Handling Advantages F To demonstrate EH advantages:  Open QuotientWithMethod.java that reads two integers and displays their quotient. F 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.

53 Assoc. Prof. Stoyan Bonev 10/20/2015 53 EH from Java to C# F Convert –QuotientWithMethod.java – to –QuotientWithMethod.cs

54 Assoc. Prof. Stoyan Bonev 10/20/2015 54 EH from Java to C#  Run and Test: QuotientWithMethod.cs

55 Assoc. Prof. Stoyan Bonev 10/20/2015 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

56 Assoc. Prof. Stoyan Bonev 10/20/2015 56 Example: Declaring, Throwing, and Catching Exceptions F 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. F Open CircleWithException.java file

57 Assoc. Prof. Stoyan Bonev 10/20/2015 57 EH from Java to C# F Convert – CircleWithException.java – to – CircleWithException.cs

58 Assoc. Prof. Stoyan Bonev 10/20/2015 58 EH from Java to C#  Run and Test; CircleWithException.cs

59 Assoc. Prof. Stoyan Bonev 10/20/2015 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

60 Assoc. Prof. Stoyan Bonev 10/20/2015 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

61 Assoc. Prof. Stoyan Bonev 10/20/2015 61 Defining Custom Exception Classes F Use the exception classes in the API whenever possible. F Define custom exception classes if the predefined classes are not sufficient. F Define custom exception classes by extending Exception or a subclass of Exception. F Open CircleWithUserException.java file

62 Assoc. Prof. Stoyan Bonev 10/20/2015 62 EH from Java to C# F Convert –CircleWithUserException.java – to –CircleWithUserException.cs

63 Assoc. Prof. Stoyan Bonev 10/20/2015 63 EH from Java to C#  Run and Test: CircleWithUserException.cs

64 Assoc. Prof. Stoyan Bonev 10/20/2015 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; } }

65 Assoc. Prof. Stoyan Bonev 10/20/2015 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

66 Assoc. Prof. Stoyan Bonev 10/20/2015 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

67 Thank You for Your attention!


Download ppt "10/20/2015Assoc. Prof. Stoyan Bonev1 COS240 O-O Languages AUBG, COS dept Lecture 37 Title: C# vs. Java Exception Handling Reference: COS240 Syllabus."

Similar presentations


Ads by Google