Exception Handling

30
Souradeep Saha Writayan Das Exception Handling

description

Exception Handling in Java and C++

Transcript of Exception Handling

Page 1: Exception Handling

Souradeep SahaWritayan Das

Exception Handling

Page 2: Exception Handling

Intr

oduc

tion

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

Page 3: Exception Handling

Intr

oduc

tion

Exception HandlingThe 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

Page 4: Exception Handling

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

Page 5: Exception Handling

Exception An unexpected error that occurs during runtime

Throwing

The process by which an exception is generated and passed to the program

CatchingCapturing 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

Page 6: Exception Handling

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 executionChecked 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

Page 7: Exception Handling

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?

Page 8: Exception Handling

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.

Page 9: Exception Handling

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.

Page 10: Exception Handling

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 -encompassingas enclosing the main() function code within a try block.

Page 11: Exception Handling

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

Page 12: Exception Handling

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

Page 13: Exception Handling

Java Exception Hierarchy

Page 14: Exception Handling

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:

Page 15: Exception Handling

C++: A Simple Example

#include <iostream>using namespace std;

int main(){

cout << "Start\n";try { // start a try block

cout << "Inside try block\n";throw 100; // throw an errorcout << "This will not execute";

}catch (int i){ // catch an error

cout << "Caught an exception -- value is: ";cout << i << "\n";

}cout << "End";return 0;

}

Output:

StartInside try blockCaught an exception -- value is: 100End

(double i)

Output:

StartInside try blockAbnormal program termination

Page 16: Exception Handling

#include <iostream>using namespace std;void Xtest(int test){

cout << "Inside Xtest, test is: " << test << "\n";if(test)

throw test;}int main(){

cout << "Start\n";try {

cout << "Inside try block\n";Xtest(0);Xtest(1);Xtest(2);

}catch (int i){

cout <<"Caught an exception -- value is: ";cout << i << "\n";

}cout << "End";return 0;

}

Output:

StartInside try blockInside Xtest, test is: 0Inside Xtest, test is: 1Caught an exception -- value is: 1End

C++: Throwing an exception from outside try block

Page 17: Exception Handling

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: -4Not Positive: -4

Page 18: Exception Handling

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 thefirst 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.

Page 19: Exception Handling

C++ 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.

Page 20: Exception Handling

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}

Page 21: Exception Handling

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

Page 22: Exception Handling

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.

Page 23: Exception Handling

#include <iostream>using namespace std;void Xhandler(){

try {

throw "hello"; }catch(const char *){

cout << "Caught char * inside Xhandler\n";

throw ; }

}int main(){

cout << "Start\n";try{

Xhandler();}catch(const char *){

cout << "Caught char * inside main\n";}cout << "End";return 0;

}

Output:

StartCaught char * inside XhandlerCaught char * inside mainEnd

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

Page 24: Exception Handling

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() .

Page 25: Exception Handling

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) ( );

Page 26: Exception Handling

#include <cstdlib>#include <exception>using namespace std;

void my_Thandler(){

cout << "Inside new terminate handler\n";abort();

}int main(){

set_terminate(my_Thandler);try{

cout << "Inside try block\n";throw 100;

}catch (double i){}

return 0;}

Output:

Inside try blockInside new terminate handlerabnormal program termination

Example: Terminate handler

Page 27: Exception Handling

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 bean 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

Page 28: Exception Handling

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";}}

Page 29: Exception Handling

Bibliography

C++: The Complete Reference. Third Edition. Herbert Schildt

www.stackoverflow.com

Page 30: Exception Handling

Thank you.