2. Introduction What is an Exception?
An exception is an unexpected event that occurs during
runtime and causes normal program flow to be disrupted.
Some common examples:
Divide by zero errors
Accessing the elements of an array beyond its range
Invalid input
Hard disk crash
Opening a non-existent file
Heap memory exhaustion
3. Introduction Exception Handling
The way of handling anomalous situations in a program-run is
known as Exception Handling.
Its advantages are:
Exception handling separates error-handling code from
normal code
It clarifies the code and enhances readability
It stimulates consequences as the error-handling takes
place at one place and in one manner
It makes for clear, robust and fault-tolerant programs
4. 1
• Write code such that it raises an error flag every
time something goes wrong
• [throw exception]
2
• Error flag is raised, then
3
• Call the Error-handling routine
• [catch exception]
Concept of Exception Handling
5. Exception An unexpected error that occurs during runtime
Throwing
The process by which an exception is generated and
passed to the program
Catching
Capturing an exception that has just occurred and
executing statements that try to resolve the problem
Catch
clause or
catch
block
The block of code that attempts to deal with the
exception
Stack
trace
The sequence of method calls that brought control to
the point where the exception occurred
Terminology
6. Java: Categories of Exception
Checked Exception
Checked exceptions are inherited from the core Java class Exception.
They represent exceptions that are frequently considered “non fatal” to
program execution
Checked exceptions must be handled in your code, or passed to parent
classes for handling
Unchecked Exception
Unchecked exceptions represent error conditions that are considered
“fatal” to program execution.
You do not have to do anything with an unchecked exception. Your
program will terminate with an appropriate error message
7. If the method contains code that may cause a checked
exception, we MUST handle the exception OR pass the
exception to the parent class (every class has Object as the
ultimate parent)
₪ To handle the exception, we write a “try-catch” block.
₪ To pass the exception “up the chain”, we declare a
throws clause in our method or class declaration.
How do we handle exceptions?
8. import java.io.*;
public class ExcepTest
{
public static void main(String args[])
{
try
{
int a[] = new int[2];
System.out.println("Access element three :" + a[3]);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Exception thrown :" + e);
}
System.out.println("Out of the block");
}
}
Java: Try-Catch MechanismWherever the code may trigger
an exception, the normal code
logic is placed inside a block of
code starting with the “try”
keyword:
After the try block, the code to
handle the exception should it
arise is placed in a block of
code starting with the
“catch” keyword.
9. try
{
//Protected code
}
catch(ExceptionType1 e1)
{
//Catch block
}
finally
{
//The finally block always executes.
}
finally keyword
The finally keyword is used to create a block of code that follows a try
block. A finally block of code always executes, whether or not an exception
has occurred.
Using a finally block allows you to run any cleanup-type statements that
you want to execute, no matter what happens in the protected code.
10. C++: General form of try and catch
try
{
// try block
}
catch (type1 arg)
{
// catch block
}
catch (type2 arg)
{
// catch block
}
catch (type3 arg)
{
// catch block
}
...
catch (typeN arg)
{
// catch block
}
Note: The try can be as
short as a few
statements within one
function or as all -
encompassing
as enclosing the main()
function code within a
try block.
11. The throw keyword
Note:
› If an exception is thrown for which there is no applicable catch statement, an
abnormal program termination may occur.
› Throwing an unhandled exception causes the standard library function terminate() to
be invoked.
› By default, terminate() calls abort() to stop the program, but we can specify our own
termination handler.
General Form:
throw exception;
— throw generates the exception specified by exception
— throw must be executed within a try block
— throw can also be executed within a function called from a try block
12. import java.io.*;
public class className
{
public void deposit(double amount)
throws Exception
{
// Method implementation
}
//Remainder of class definition
}
Java: Passing the Exception
In any method that
might throw an
exception, you may
declare the method as
“throws” that
exception, and thus
avoid handling the
exception yourself
14. Java: Creating Exceptions
class WordContainsException extends Exception
{
//Parameterless Constructor
public WordContainsException(){}
//Constructor that accepts a message
public WordContainsException(String message)
{
super(message);
}
}
try
{
if(word.contains(" "))
{
throw new WordContainsException();
}
}
catch(WordContainsException ex)
{
//Process message however you would like
}
Usage:
15. C++: A Simple Example
#include <iostream>
using namespace std;
int main()
{
cout << "Startn";
try
{ // start a try block
cout << "Inside try blockn";
throw 100; // throw an error
cout << "This will not execute";
}
catch (int i)
{ // catch an error
cout << "Caught an exception --
value is: ";
cout << i << "n";
}
cout << "End";
return 0;
}
Output:
Start
Inside try block
Caught an exception -
- value is: 100
End
(double i)
Output:
Start
Inside try block
Abnormal program
termination
16. #include <iostream>
using namespace std;
void Xtest(int test)
{
cout << "Inside Xtest, test is: " << test << "n";
if(test)
throw test;
}
int main()
{
cout << "Startn";
try
{
cout << "Inside try blockn";
Xtest(0);
Xtest(1);
Xtest(2);
}
catch (int i)
{
cout <<"Caught an exception -- value is: ";
cout << i << "n";
}
cout << "End";
return 0;
}
Output:
Start
Inside try block
Inside Xtest, test is: 0
Inside Xtest, test is: 1
Caught an exception --
value is: 1
End
C++: Throwing an exception from outside try block
17. Catching Class Types: An Example
#include <iostream>
#include <cstring>
using namespace std;
class MyException
{
public:
char str_what[80];
int what;
MyException()
{
*str_what = 0;
what =0;
}
MyException(char *s, int e)
{
strcpy(str_what, s);
what = e;
}
};
int main()
{
int i;
try
{
cout << "Enter a positive
number: ";
cin >> i;
if(i<0)
throw MyException("Not
Positive", i);
}
catch (MyException e)
{
cout << e.str_what << ": ";
cout << e.what << "n";
}
return 0;
}
Sample run:
Enter a positive
number: -4
Not Positive: -4
18. Handling Derived-Class Exceptions
#include <iostream>
using namespace std;
class B
{};
class D: public B
{};
int main()
{
D derived;
try
{
throw derived;
}
catch(B b)
{
cout << "Caught a base class.n";
}
catch(D d)
{
cout << "This won't execute.n";
}
return 0;
}
Note:
Here, because derived
is an object that has B
as a base class, it
will be caught by the
first catch clause and
the second clause will
never execute.
Some compilers will
flag this condition
with a warning message.
Others may issue an
error. Either way, to
fix this condition, we
should reverse the
order of the catch
clauses.
19. Exception Handling Options
There are several additional features and nuances to C++ exception handling that
make it easier and more convenient to use. These attributes are discussed here.
20. Catching All Exceptions
In some circumstances we want an exception
handler to catch all exceptions instead of just a
certain type.
This is easily accomplished by using this form of
catch:
catch(...)
{
// process all exceptions
}
21. Restricting Exceptions
A throw clause is added to a function definition to specify
which types of exceptions it can throw as shown below:
ret-type func-name(arg-list) throw(type-list)
{
//…
}
Note:
› only those data types contained in the comma-separated type-list may be thrown by
the function
› throwing any other type of expression will cause abnormal program termination
› if we don't want a function to be able to throw any exceptions, then we use an
empty list
22. Restricting Exceptions (continued…)
What happens when an unsupported exception is thrown?
Standard library function
unexpected() is called
By default, unexpected()
calls abort(), that
abnormally terminates the
program
However, we can specify our
own unexpected handler, as
discussed later.
Note:
⁻ a function can be
restricted only in what
types of exceptions it
throws back to the try
block that called it.
⁻ a try block within a
function may throw any
type of exception so
long as it is caught
within that function.
23. #include <iostream>
using namespace std;
void Xhandler()
{
try
{
throw "hello";
}
catch(const char *)
{
cout << "Caught char * inside
Xhandlern";
throw ;
}
}
int main()
{
cout << "Startn";
try
{
Xhandler();
}
catch(const char *)
{
cout << "Caught char * inside mainn";
}
cout << "End";
return 0;
}
Output:
Start
Caught char * inside
Xhandler
Caught char * inside main
End
C++: Rethrowing an exception
Note:
₪ this causes the current
exception to be passed on
to an outer try/catch
sequence
₪ when we rethrow an
exception, it will be caught
by the next catch statement
in the hierarchy
24. terminate() and unexpected()
void terminate() and void unexpected() are standard C++ library functions that are
called when something goes wrong during the process of exception handling.
Note:
₪ In general, terminate() is the handler of last resort when
no other handlers for an exception are available. By
default, terminate() calls abort().
terminate() is called in the following circumstances:
₪ whenever the exception handling subsystem fails to find
a matching catch statement for an exception.
₪ It is also called if our program attempts to rethrow an
exception when no exception was originally thrown.
₪ is also called under various other, more obscure
circumstances.
The unexpected() function
is called when a function
attempts to throw an
exception that is not
allowed by its throw list.
By default, unexpected()
calls terminate() .
25. Setting the Terminate and Unexpected Handlers
To change the terminate handler, we use set_terminate() , shown here:
terminate_handler set_terminate(terminate_handler newhandler) throw( );
Here, newhandler is a pointer to the new terminate handler. The function returns a pointer to
the old terminate handler. The new terminate handler must be of type
terminate_handler, which is defined like this:
typedef void (*terminate_handler) ( );
To change the unexpected handler, use set_unexpected() , shown here:
unexpected_handler set_unexpected(unexpected_handler newhandler) throw( );
Here, newhandler is a pointer to the new unexpected handler. The function returns a pointer
to the old unexpected handler. The new unexpected handler must be of type
unexpected_handler, which is defined like this:
typedef void (*unexpected_handler) ( );
27. The uncaught_exception( ) Function
The C++ exception handling subsystem supplies one useful function:
uncaught_exception(). Its prototype is shown here:
bool uncaught_exception( );
This function returns true if an exception has been thrown but not yet caught. Once
caught, the function returns false.
The exception and bad_exception Classes
When a function supplied by the C++ standard library throws an exception, it will be
an object derived from the base class exception.
An object of the class bad_exception can be thrown by the unexpected handler.
These classes require the header <exception>.
Miscellaneous
28. Implementing in a program: An Example
#include <iostream>
using namespace std;
void divide(double a, double b);
int main()
{
double i, j;
do
{
cout << "Enter numerator
(0 to stop): ";
cin >> i;
cout << "Enter denominator: ";
cin >> j;
divide(i, j);
}
while(i != 0);
return 0;
}
void divide(double a, double b)
{
try
{
if(!b) throw b;
cout << "Result: " << a/b
<< endl;
}
catch (double b)
{
cout << "Result: Infinity";
}
}
This presentation demonstrates the new capabilities of PowerPoint and it is best viewed in Slide Show. These slides are designed to give you great ideas for the presentations you’ll create in PowerPoint 2010!For more sample templates, click the File tab, and then on the New tab, click Sample Templates.