Download presentation
Presentation is loading. Please wait.
1
Reference: COS240 Syllabus
COS240 O-O Languages AUBG, COS dept Lecture 37 Title: C# vs. Java Exception Handling Reference: COS240 Syllabus 6/16/2018 Assoc. Prof. Stoyan Bonev
2
Assoc. Prof. Stoyan Bonev
Lecture Contents: Errors, Bugs, Exceptions EH Techniques Exception Classes Sample demo programs 6/16/2018 Assoc. Prof. Stoyan Bonev
3
Debugging and Handling Exceptions
12 C# Programming: From Problem Analysis to Program Design 3rd Edition C# Programming: From Problem Analysis to Program Design C# Programming: From Problem Analysis to Program Design 3 Source: Longman dictionary 1987 3
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 C# Programming: From Problem Analysis to Program Design 4 Source: Longman dictionary 1987 4
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 C# Programming: From Problem Analysis to Program Design 5 Source: Longman dictionary 1987 5
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 C# Programming: From Problem Analysis to Program Design 6 Source: Longman dictionary 1987 6
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 C# Programming: From Problem Analysis to Program Design 7 Source: Longman dictionary 1987 7
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 C# Programming: From Problem Analysis to Program Design 8 Source: Longman dictionary 1987 8
9
Next slide of High Importance Raising an Exception
C# Programming: From Problem Analysis to Program Design C# Programming: From Problem Analysis to Program Design 9 Source: Longman dictionary 1987 9
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 C# Programming: From Problem Analysis to Program Design 10 Source: Longman dictionary 1987 10
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 C# Programming: From Problem Analysis to Program Design 11 Source: Longman dictionary 1987 11
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 C# Programming: From Problem Analysis to Program Design 12 Source: Longman dictionary 1987 12
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 C# Programming: From Problem Analysis to Program Design 13 Source: Longman dictionary 1987 13
14
Notice square brackets indicate optional entry
{ // Statements } catch [ (ExceptionClassName exceptionIdentifier) ] // Exception handler statements [additional catch clauses] [ finally } ] Notice square brackets indicate optional entry One catch clause required finally clause optional C# Programming: From Problem Analysis to Program Design C# Programming: From Problem Analysis to Program Design 14 Source: Longman dictionary 1987 14
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 C# Programming: From Problem Analysis to Program Design 15 Source: Longman dictionary 1987 15
16
Use of Generic Catch Clause
Example 11-2 uses a generic catch block Figure Generic catch block handles the exception C# Programming: From Problem Analysis to Program Design C# Programming: From Problem Analysis to Program Design 16 Source: Longman dictionary 1987 16
17
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 Exceptions – division by zero and programmer errors C# Programming: From Problem Analysis to Program Design C# Programming: From Problem Analysis to Program Design 17 Source: Longman dictionary 1987 17
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 C# Programming: From Problem Analysis to Program Design 18 Source: Longman dictionary 1987 18
19
Exception Object (continued)
catch (System.Exception e) { Console.Error.WriteLine("Problem with scores - " + "Can not compute average"); Console.Error.WriteLine(e.Message); } Figure Use of Message property with the exception object C# Programming: From Problem Analysis to Program Design C# Programming: From Problem Analysis to Program Design 19 Source: Longman dictionary 1987 19
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 C# Programming: From Problem Analysis to Program Design 20 Source: Longman dictionary 1987 20
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 C# Programming: From Problem Analysis to Program Design 21 Source: Longman dictionary 1987 21
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 C# Programming: From Problem Analysis to Program Design 22 Source: Longman dictionary 1987 22
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 C# Programming: From Problem Analysis to Program Design 23 Source: Longman dictionary 1987 23
24
SystemException Class
C# Programming: From Problem Analysis to Program Design C# Programming: From Problem Analysis to Program Design 24 Source: Longman dictionary 1987 24
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 C# Programming: From Problem Analysis to Program Design 25 Source: Longman dictionary 1987 25
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 C# Programming: From Problem Analysis to Program Design 26 Source: Longman dictionary 1987 26
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 C# Programming: From Problem Analysis to Program Design 27 Source: Longman dictionary 1987 27
28
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 C# Programming: From Problem Analysis to Program Design C# Programming: From Problem Analysis to Program Design 28 Source: Longman dictionary 1987 28
29
User-defined class 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 C# Programming: From Problem Analysis to Program Design 29 Source: Longman dictionary 1987 29
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 C# Programming: From Problem Analysis to Program Design 30 Source: Longman dictionary 1987 30
31
static double GetResults (double value1, double value2) {
if (value2 < ) // 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 C# Programming: From Problem Analysis to Program Design 31 Source: Longman dictionary 1987 31
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 C# Programming: From Problem Analysis to Program Design 32 Source: Longman dictionary 1987 32
33
Input Output (IO) Exceptions (continued)
C# Programming: From Problem Analysis to Program Design C# Programming: From Problem Analysis to Program Design 33 Source: Longman dictionary 1987 33
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 C# Programming: From Problem Analysis to Program Design 34
35
Assoc. Prof. Stoyan Bonev
6/16/2018 Assoc. Prof. Stoyan Bonev
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 6/16/2018
37
EH from Java to C# Convert Quotient.java to Quotient.cs 6/16/2018
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. 6/16/2018
39
EH from Java to C# Convert QuotientWithIF.java to QuotientWithIF.cs
6/16/2018
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 6/16/2018
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"); 6/16/2018
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 6/16/2018
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"); 6/16/2018
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 6/16/2018
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"); } 6/16/2018
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 6/16/2018
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); } 6/16/2018
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 6/16/2018
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); } 6/16/2018
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 6/16/2018
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"); catch (System.Exception e) Console.Error.WriteLine("Problem with data - cannot compute quotient - level 3"); 6/16/2018
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. 6/16/2018 Source: Longman dictionary 1987
53
EH from Java to C# Convert QuotientWithMethod.java to
QuotientWithMethod.cs 6/16/2018
54
EH from Java to C# Run and Test: QuotientWithMethod.cs 6/16/2018
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 6/16/2018
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 6/16/2018
57
EH from Java to C# Convert CircleWithException.java to
CircleWithException.cs 6/16/2018
58
EH from Java to C# Run and Test; CircleWithException.cs 6/16/2018
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 6/16/2018
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 6/16/2018
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 6/16/2018
62
EH from Java to C# Convert CircleWithUserException.java to
CircleWithUserException.cs 6/16/2018
63
EH from Java to C# Run and Test: CircleWithUserException.cs 6/16/2018
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; } 6/16/2018
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 6/16/2018
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 6/16/2018
67
Thank You for Your attention!
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.