* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Download COS240Lec37_CSEH - To Parent Directory
Design Patterns wikipedia , lookup
Name mangling wikipedia , lookup
Go (programming language) wikipedia , lookup
Java syntax wikipedia , lookup
JavaScript syntax wikipedia , lookup
Class (computer programming) wikipedia , lookup
Reactive programming wikipedia , lookup
Java (programming language) wikipedia , lookup
Falcon (programming language) wikipedia , lookup
Error detection and correction wikipedia , lookup
Control flow wikipedia , lookup
Java performance wikipedia , lookup
Object-oriented programming wikipedia , lookup
C Sharp syntax wikipedia , lookup
COS240 O-O Languages
AUBG, COS dept
Lecture 37
Title:
C# vs. Java
Exception Handling
Reference: COS240 Syllabus
5/24/2017
Assoc. Prof. Stoyan Bonev
1
Lecture Contents:
• Errors, Bugs, Exceptions
• EH Techniques
• Exception Classes
• Sample demo programs
5/24/2017
Assoc. Prof. Stoyan Bonev
2
12
Debugging
and
Handling Exceptions
C# Programming: From Problem Analysis to Program Design
3rd Edition
C# Programming: From Problem Analysis to Program Design
3
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
4
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
5
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
6
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
7
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
8
Raising an Exception
Next slide
of
High Importance
C# Programming: From Problem Analysis to Program Design
9
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
10
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
11
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
12
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
13
try
{
Notice square
brackets indicate
optional entry
// Statements
}
catch [ (ExceptionClassName exceptionIdentifier) ]
{
// Exception handler statements
}
[additional catch clauses]
One catch
clause
required
[ finally
finally clause
optional
{
// Statements
}]
C# Programming: From Problem Analysis to Program Design
14
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
15
Use of Generic Catch Clause
Example 11-2
uses a generic catch block
Figure 12-14 Generic catch block handles the exception
C# Programming: From Problem Analysis to Program Design
16
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
C# Programming: From Problem Analysis to Program Design
17
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
18
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
19
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
20
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
21
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
22
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
23
SystemException Class
C# Programming: From Problem Analysis to Program Design
24
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
25
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
26
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
27
Custom Exceptions (continued)
public class FloatingPtDivisionException :
System.ApplicationException
{
String
public FloatingPtDivisionException
argument sent
(string exceptionType)
to the base
: base (exceptionType)
constructor
{
indicating type
// Empty body
of exception
}
}
C# Programming: From Problem Analysis to Program Design
28
public class TestOfCustomException
{
static void Main(string[] args)
{
double value1 = 0, value2=0, answer;
try
{ //Could include code to enter new values.
Useranswer = GetResults(value1, value2);
defined }
class catch (FloatingPtDivisionException excepObj)
{
Console.Error.WriteLine(excepObj.Message);
}
catch
{
Console.Error.WriteLine(“Something else happened!”);
}
}
C# Programming: From Problem Analysis to Program Design
29
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
30
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;
Throwing an
}
exception
return value1 / value2;
}
}
C# Programming: From Problem Analysis to Program Design
31
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
32
Input Output (IO) Exceptions
(continued)
C# Programming: From Problem Analysis to Program Design
33
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
5/24/2017
Assoc. Prof. Stoyan Bonev
35
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
5/24/2017
Assoc. Prof. Stoyan Bonev
36
EH from Java to C#
Convert
– Quotient.java
– to
– Quotient.cs
5/24/2017
Assoc. Prof. Stoyan Bonev
37
EH from Java to C#
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.
Simple
user specified if stmt to test for zero
valued divisor.
Explicit
5/24/2017
Assoc. Prof. Stoyan Bonev
38
EH from Java to C#
Convert
– QuotientWithIF.java
– to
– QuotientWithIF.cs
5/24/2017
Assoc. Prof. Stoyan Bonev
39
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
5/24/2017
Assoc. Prof. Stoyan Bonev
40
Exception-Handling Overview
try {
System.out.print("Enter the dividend: ");
System.out.print("Enter the divisor: ");
dividend = console.nextInt();
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");
}
5/24/2017
Assoc. Prof. Stoyan Bonev
41
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
5/24/2017
Assoc. Prof. Stoyan Bonev
42
Exception-Handling Overview
try {
System.out.print("Enter the dividend: ");
System.out.print("Enter the divisor: ");
dividend = console.nextInt();
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");
}
5/24/2017
Assoc. Prof. Stoyan Bonev
43
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
5/24/2017
Assoc. Prof. Stoyan Bonev
44
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");
}
5/24/2017
Assoc. Prof. Stoyan Bonev
45
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
5/24/2017
Assoc. Prof. Stoyan Bonev
46
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);
}
5/24/2017
Assoc. Prof. Stoyan Bonev
47
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
5/24/2017
Assoc. Prof. Stoyan Bonev
48
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);
}
5/24/2017
Assoc. Prof. Stoyan Bonev
49
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
5/24/2017
Assoc. Prof. Stoyan Bonev
50
EH from Java to C#
try
{
Console.Write("Enter the dividend: ");
Console.Write("Enter the divisor: ");
dividend = Convert.ToInt32(Console.ReadLine());
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);
}
5/24/2017
Assoc. Prof. Stoyan Bonev
51
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.
5/24/2017
Assoc. Prof. Stoyan Bonev
52
EH from Java to C#
Convert
– QuotientWithMethod.java
– to
– QuotientWithMethod.cs
5/24/2017
Assoc. Prof. Stoyan Bonev
53
EH from Java to C#
Run
5/24/2017
and Test: QuotientWithMethod.cs
Assoc. Prof. Stoyan Bonev
54
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: ");
Console.Write("Enter the divisor: ");
dividend = Convert.ToInt32(Console.ReadLine());
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 Bonev
5/24/2017
55
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
5/24/2017
Assoc. Prof. Stoyan Bonev
56
EH from Java to C#
Convert
– CircleWithException.java
– to
– CircleWithException.cs
5/24/2017
Assoc. Prof. Stoyan Bonev
57
EH from Java to C#
Run
5/24/2017
and Test; CircleWithException.cs
Assoc. Prof. Stoyan Bonev
58
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
5/24/2017
Assoc. Prof. Stoyan Bonev
59
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
5/24/2017
Assoc. Prof. Stoyan Bonev
60
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
5/24/2017
Assoc. Prof. Stoyan Bonev
61
EH from Java to C#
Convert
– CircleWithUserException.java
– to
– CircleWithUserException.cs
5/24/2017
Assoc. Prof. Stoyan Bonev
62
EH from Java to C#
Run
and Test:
CircleWithUserException.cs
5/24/2017
Assoc. Prof. Stoyan Bonev
63
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; }
}
5/24/2017
Assoc. Prof. Stoyan Bonev
64
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
5/24/2017
Assoc. Prof. Stoyan Bonev
65
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
} //5/24/2017
end of class Program
Assoc. Prof. Stoyan Bonev
66
Thank You
for
Your attention!