sas

ASP-Active Server Pages
Computer Fundamentals
What is computer?
Software
Hardware
Operating System
Programming Language
C and C++
Java
C#
Python
Visual Basic
Jscript.NET
Web Development
HTML
ASP
PHP
JavaScript
VBScript
.NET
.NET Micrsoft
ASP.NET
.NET Mobile
Forum
VB/VB.NET
ASP/ASP.NET
VBScript
JavaScript

Topic: C++-Language


Exception Handling
An exception is a situation that would be unusual for the program that is being processed. As a programmer, you should anticipate any abnormal behavior that could be caused by the user entering wrong information that could otherwise lead to unpredictable results.

An error result or an unpredictable behavior on your program not caused by the operating system but that occurs in your program is called an exception. The ability to deal with a program’s eventual abnormal behavior is called exception handling. C++ provides three keywords to handle an exception.

1. Trying the normal flow: To deal with the expected behavior of a program, use the try keyword as in the following syntax:

try {Behavior}

The try keyword is required. It lets the compiler know that you are anticipating an abnormal behavior and will try to deal with it. The actual behavior that needs to be evaluated is included between an opening curly bracket “{“ and a closing curly bracket “}”. Inside of the brackets, implement the normal flow that the program should follow, at least for this section of the code.
2. Catching Errors: During the flow of the program as part of the try section, if an abnormal behavior occurs, instead of letting the program crash or instead of letting the compiler send the error to the operating system, you can transfer the flow of the program to another section that can deal with it. The syntax used by this section is:

catch(Argument) {WhatToDo}

This section always follows the try section and there must not be any code between the try’s closing bracket and the catch section. The catch keyword is required and follows the try section. The catch behaves a little like a function. It uses an argument that is passed by the previous try section. The argument can be a regular variable or a class. If there is no argument to pass, the catch must at least take a three-period argument as in catch(…). The behavior of the catch clause starts with an opening curly bracket “{“ and ends with a closing curly bracket “}”. The inside of the brackets is called the body of the catch clause. Therefore, use the body of the catch to deal with the error that was caused.


// exceptions
#include <iostream.h>

int main () {
char myarray[10];
try
{
for (int n=0; n<=10; n++)
{
if (n>9) throw "Out of range";
myarray[n]='z';
}
}
catch (char * str)
{
cout << "Exception: " << str << endl;
}
return 0;
}























Output

Exception: Out of range




Prev

 







 


 

Error in my_thread_global_end(): 1 threads didn't exit