19 Exceptions
19 Exceptions
Exceptions
• Errors that occur at run time
• Examples
– Running out of memory
– Unable to open a file
– Divide by zero
– Assigning an invalid value
– Out of bounds index
– ….
Exception Handling
• If without handling,
• Program crashes
• Falls into unknown state
• An exception handler is a section of
program code that is designed to
execute when a particular exception
occurs
• Resolve the exception
• Lead to known state, such as
exiting the program
Exception Handling
• Keywords
– Try
– Throw
– Catch
Why we need Exceptions?
• C-language programs often signal an
error by returning a particular value
from the function in which it occurred.
• For example, disk-file functions often
return NULL or 0 to signal an error.
• Each time you call one of these
functions you check the return value.
Why we need Exceptions?
if( somefunc() == ERROR_RETURN_VALUE )
//handle the error or call error-handler function
else
//proceed normally
if( thirdfunc() == 0 )
//handle the error or call error-handler function
else
//proceed normally
Exception Syntax
class AnError //exception class
{
};
//-----------------------------------------------------------
Distance() //constructor (no args)
{ feet = 0; inches = 0.0; }
//-----------------------------------------------------------
Distance(int ft, float in) //constructor (two args)
{
if(in >= 12.0) //if inches too big,
throw InchesEx(); //throw exception
feet = ft;
inches = in;
void getdist() //get length from user
{
cout << "\nEnter feet: ";
cin >> feet;
cout << "Enter inches: ";
cin >> inches;
if(inches >= 12.0) //if inches too big,
throw InchesEx(); //throw exception
}
//--------------------------------------------------
};
void main()
{
try
{
Distance dist1(17, 3.5);
Distance dist2;
dist2.getdist();
cout << "\ndist1 = "; dist1.showdist();
cout << "\ndist2 = "; dist2.showdist();
}
catch(InchesEx e) //catch exceptions
{
cout << "\nInitialization error: "
cout << “Inches value is too large.";
}
class Error {
private:
string message;
public:
Error(string s) { message = s; }
string getMessage() { return message; }
};
Exceptions with Arguments
class Rectangle {
private:
int l;
int w;
public:
Rectangle(int l, int w) {
if (l <= w)
throw Error("Length must be greater
than width");
this->l = l;
this->w = w;
}
};
Exceptions with Arguments
void main()
{
try {
Rectangle r(2, 10);
}
catch (Error e) {
cout << "Error:" << e.getMessage();
}
}
Exceptions with Arguments
class Distance
{
private:
int feet;
float inches;
public: