Handling Run-time Errors with Exceptions
#include <cstring>
#include <iostream>
using namespace std;
Define a class to represent the exception
(=error) and to store information about the exception.
class DivideByZeroException
{
public:
DivideByZeroException(
/* in */ int initError )
{
error =
initError;
}
int
GetError( )
{
return
error;
}
private:
int error;
};
Throw the exception.
int Divide( /* in */ int i, /* in */ int j )
{
if ( j == 0
)
{
DivideByZeroException
e( 5120 );
throw e;
}
alternate
code uses a temporary object: throw
DivideByZeroException( 5120 );
return i /
j;
}
Try a piece of code and catch any exceptions
that occur within the piece of code.
void main()
{
int i =
1000;
int j = 0;
try
{
i =
Divide( i, j );
}
catch (
DivideByZeroException e )
{
cout
<< "Divide by Zero. Error# " << e.GetError()
<< endl;
}
}
Exception Hierachies
Exception
classes can be organized into hierarchies.
class MathException { ... };
![]()
class DivideByZeroException : public
MathException { ... }
class OverflowException : public
MathException { ... }
try
{
i =
Divide( i, j );
}
catch (
DivideByZeroException e )
{
...
}
catch (
MathException e ) // catch all
other MathException-s
{
...
}
catch ( ...
) // catch everything else
{
...
}
The Standard Exception Classes
exception
logic_error
invalid_arguemnt
out_of_range
...
runtime_error
overflow_error
...
bad_alloc thrown when the
heap is exhausted
try { for (
;; ) new char[10000]; } catch ( bad_alloc) { cerr
<< "Heap exhausted" << endl; }