Exceptions
Exceptions
C++ ERRORS
SYNTAX ERROR
• Compile-time error • Missing semicolon
• Violation in syntax or writing • Mismatched symbols
technique • Incorrect operator
• Flagged by compiler prior to
compilation
RUNTIME ERRORS
• Occur during runtime • Infinite recursion
• Typically an error in operation • Index out of bounds
• Division by zero
LOGICAL ERRORS
• Also called semantic errors • Possible causes are limitless, vary
• Glitches/bugs by project
• Occur during runtime
• Program exhibits undesired
behavior
• Only detectable via testing
LINKER ERRORS
• Occur after compilation, before • Incorrect function prototyping
runtime • Incorrect reference to header file
• Failure in linking of object files • “Main” instead of “main”
FIXING ERRORS
• Most errors easily fixed by correcting existing code
• Correct object references
• Ensure proper syntax is used
• Fix order of operators and expressions
• Some require a more dynamic solution
• If-statements are useful but limited
• Can only catch specific errors
EXCEPTION HANDLING
WHAT ARE EXCEPTIONS?
• Exception – Error that occurs during runtime
• Dozens of exception types
• C++ keywords for exception handling
• try – Attempts to execute some block of code
• throw – Raises an exception and looks for a catch block
• catch – Handles exceptions thrown from try block
• Advantages
• Separation of code
• Control over exceptions thrown
• Grouping of error types
try{
int dividend = 32;
int divisor = 0;
int quotient;
SYNTAX if(divisor == 0){
throw runtime_error(
Begin with try block "Cannot divide by zero!\n");
throw statements occur somewhere in }
the try block quotient = dividend/divisor;
try block followed by catch block cout<< quotient << endl;
The what function returns the error }
thrown catch(const exception &e){
cout<< "Exception " << e.what() << endl;
}
TRY-CATCH – NOT ALWAYS
APPROPRIATE