answersLogoWhite

0


Best Answer

Exception handling is a programming language construct or computer hardware mechanism designed to handle the occurrence of exceptions, special conditions that change the normal flow of program execution

User Avatar

Wiki User

13y ago
This answer is:
User Avatar
More answers
User Avatar

Wiki User

9y ago

Whenever an exception is thrown, the function call stack is unwound until a suitable exception handler is found. If the call stack is unwound all the way back to the main function and no suitable handler is found there, the program automatically invokes abort(). The operating system will then typically inform you that the program has stopped working (in other words, it has crashed).

Exceptions need not be thrown from inside a try block in order to be caught provided at least one function upon the call stack provides a suitable catch block to handle the exception. In that sense the code IS within a try block since you cannot have a catch block unless there's at least one function on the call stack with a try block.

Once an exception is thrown, that exception is said to be "in flight" as it is passed down through the unwinding call stack. As soon as a catch block is encountered that is capable of handling the exception, the exception is said to be "caught" and the stack stops unwinding at that point. Any variables or functions that were previously on the call stack will no longer be available -- they have fallen from scope.

As soon as an exception is caught, it is said to be handled. However, in some cases a handler might only be able to perform a partial recovery and must allow other handlers further down the call stack to perform other recovery tasks. This can be achieved either by rethrowing the same exception or by throwing a new exception.

It is vital that your code does not throw an exception whilst an exception is "in flight". As the call stack unwinds, destructors will be invoked as objects fall from scope. For that reason, destructors must not throw exceptions. If a destructor could throw an exception, it must be handled by the destructor itself. It is also vital that your code does not throw exceptions that cannot be caught. If the exception-handling mechanism catches you doing either, it will terminate your program.

Always provide a catch-all exception handler in your main function. If the stack unwinds to the main function, then this is your last chance to attempt recovery before the program terminates and crashes. At the very least you should log the error. If you've designed your program to make use of RAII (resource acquisition is initialisation), then all resources will be recovered during the stack unwinding process. RAII and exception-handling are two-sides of the same coin; you cannot have one without the other.

The most common problem when dealing with exceptions is how to deal with raw pointers because raw pointers do not support RAII. The answer is simple: use smart pointers or resource handles instead. If you encapsulate a raw pointer within a class that is guaranteed not to throw an exception, you simply cannot go wrong. If an exception occurs outside of the class, forcing an object of the class to fall from scope as the stack unwinds, its destructor will ensure its resources are returned to the system automatically. In other words, it's a free and efficient garbage collector that greatly simplifies exception handling to the point the handlers need only log the errors; the objects themselves perform the all-important cleanup tasks automatically.

This answer is:
User Avatar

User Avatar

Wiki User

9y ago

Exception objects are the fundamental means by which exceptions are thrown and caught within C++. It is important to note that exception objects cannot be used to catch exceptions thrown by the underlying hardware. For instance, the following line will throw a hardware exception:

int z = 1 / 0; // exception: integer divide by zero!

Even if you were to put this line into a try-catch block, there is no way to catch the exception itself because the catch block can only catch exception objects thrown by your code. Hardware exceptions are not exception objects, nor can they be used to construct an exception object. When your code causes a hardware exception, your code automatically has undefined behaviour and is therefore an invalid program.

To handle an exception within C++ your code must throw an exception and you must provide a handler for that exception. If there is no handler, an unhandled exception is thrown and your program has undefined behaviour. It may crash, it may wipe your hard-drive, a patient could die, it may wipe billions off your stocks. Anything is possible when behaviour is undefined. Remember the first rule of programming: never allow a program with undefined behaviour to execute outside of a debugger. The second rule of programming: NEVER ALLOW A PROGRAM WITH UNDEFINED BEHAVIOUR TO EXECUTE OUTSIDE OF A DEBUGGER!!

It is important to note that not all exceptions need to be handled. Some can be easily prevented with trivial workarounds. For instance, the divide by zero hardware exception can be easily avoided simply by ensuring the denominator in any division is non-zero before invoking the division operator. Make good use of assertions to ensure that your assumptions hold true at all times -- and test them thoroughly! An exception handler is only required when an assertion cannot be guaranteed to be true. Exceptions are exceptional circumstance and should only be used as such. Whenever you call a new function you are not familiar with, check its documentation to see what exceptions it may throw and handle each accordingly.

When you need an exception handler, you must separate the code that throws the exception from the code that handles the exception. This is achieved by placing the exceptional code in a separate function from the code that handles the exception. This is because exceptions thrown by a function are automatically caught by the function that called the exceptional function -- provided that function has a handler. If not, an unhandled exception is thrown and caught by the debugger instead. Third-party functions that throw exceptions are already separate from the calling code (i.e., your own code), but you may need to re-factor your own code. In particular, you cannot throw an exception from main since main has no caller to handle its exceptions.

The major exception classes utilised by the standard library are all defined in the header which includes the header that defines the base classes. All standard library objects and functions that throw exceptions will include these headers so the only time you really need to include them is when defining user-defined (custom) exception classes. Typically you will derive from the generic std::logic_error or std::runtime_error, both of which derive from the std::exception base class.

To throw an exception, use the throw keyword. By itself this is useless because in order to catch an exception you need to know what type of exception was thrown, and the only way to do that is through an exception object. Typically you will construct and throw an exception object in a single statement. For example:

void divide(int numerator, int denominator)

{

if (!denominator) throw std::out_of_range ("Integer divide by zero!");

return numerator / denominator;

}

However, if you have a more complex custom exception, you can construct your exception object, initialise it accordingly and then throw it.

In the calling function you place the exceptional call in a try-catch block:

std::cin >> x >> y; // unchecked input.

try

{

divide (x, y);

}

catch (std::exception& e)

{

std::cerr << e.what() << std::endl; // optional

}

Calling e.what() will return the string specified when the object was constructed. In this case "Integer divide by zero!" will be returned.

Note that you must catch the exception by reference. This ensures that you catch anything derived from std::exception (including std::out_of_range). However, if you know the specific type of exception type to expect, you can specify the type explicitly. However, in order to cater for derivatives of that type, you must catch by reference to take advantage of runtime polymorphism.

If the exceptional function could throw one of several exceptions where each needs dedicated handling, you can cater for each with additional catch blocks -- one for each type. However note that only one exception will thrown with each call to the function.

try

{

// invoke the function that might throw an exception here

}

catch (std::out_of_range& e)

{

std::cerr << "Out of range error: " << e.what() << std::endl; // optional

}

catch (std::bad_alloc& e)

{

std::cerr << "Bad allocation error: " << e.what() << std::endl; // optional

}

catch (...)

{

std::cerr << "Unknown exception: " << e.what() << std::endl; // optional

}

Typically you use catch(...) to catch any unspecified exceptions not handled by any of the preceding catch blocks.

When you define your own exception classes you can include additional information not included in the standard exceptions. At the very least you should always include some brief informational text that can be used as output to the standard error output stream via the std::exception::what() member.

Note that throwing an exception does not guarantee an exception will be caught. If there is no handler for the exception that was thrown, your program will have undefined behaviour because execution will continue with the statement immediately after the throw statement -- which could be disastrous since that is the very statement you were trying to avoid by throwing an exception in the first place. By providing a handler to catch the exception, execution passes immediately to the catcher and disaster can be averted as gracefully as possible.

This answer is:
User Avatar

User Avatar

Wiki User

13y ago

With C++ exception handling, your program can communicate unexpected events to a higher execution context that is better able to recover from such abnormal events. These exceptions are handled by code that is outside the normal flow of control.

This answer is:
User Avatar

User Avatar

Wiki User

10y ago

The try, throw and catch keywords are used to provide exception handling in C++. You can use the throw keyword to throw an exception but in order to handle the exception you must throw from within a try block and you must provide a handler for each type of exception that might be thrown.

Typically you will only use throw by itself within class constructors whenever there is a chance that allowing construction to continue would leave an invalid object. For instance, if a constructor expected a real integer (non-zero and positive) but you inadvertently passed zero, there is no way to construct the object in any meaningful way so it would be prudent to throw an exception. If you run the program in debug mode you can then trace back to determine why zero was passed in the first place and fix the error in your code.

For all other exceptions you will use try and catch wherever an exception might occur and thus allow a graceful exit rather than allowing your program to simply crash. For instance, if you were to attempt to allocate a dynamic array with 0x7fffffff elements, the chances are extremely high that the allocation will fail. In this case you will want to catch the exception and handle it yourself. The following example demonstrates this:

#include <iostream>

#include <exception>

using namespace std;

int main ()

{

try

{

char* myarray = new char[0x7fffffff];

}

catch (exception& e)

{

cout << "Standard exception: " << e.what() << endl;

}

if (myarray) delete [] myarray;

}

This program will never crash, even if an exception occurs. Although you should try and catch all exceptions where an exception might occur, there are often better ways. For instance, if an allocation returns a NULL pointer when there is insufficient memory to allocate a contiguous block of the required size, there is no need to handle the exception because the exception has already been handled (hence NULL was returned). You need only test the pointer is non-NULL before using the pointer.

This answer is:
User Avatar

User Avatar

Wiki User

9y ago

#include <iostream>

#include <string>

#include <exception>

#include <stdexcept>

void handle_eptr (std::exception_ptr eptr)

{

try

{

if (eptr)

std::rethrow_exception (eptr);

}

catch (const std::exception& e)

{

std::cerr << "Exception: "" << e.what() << ""\n";

}

}

int main()

{

try

{

// place code that may throw an exception here:

std::string().at(1); // throws "invalid string position"

}

catch(...) // catch-all

{

// perform any necessary cleanup here before calling the handler

handle_eptr (std::current_exception());

}

}

This answer is:
User Avatar

User Avatar

Wiki User

11y ago

Consider the code:

if(a/b==1)

{

//Perform some logic

}

else

{

//Perform another logic

}

here if the value of b becomes 0, execution of this code would be terminated at the point of performing the arthimetic between a and b(since a number divided by 0 yields to an undefined result) . We don't have any additional features to check this arthimetic calculation in c(I refer to checking if the denominator is 0 at run time); But exception handling in c++ allows to catch this error. This feature of c++ is called as exception handling. Similar is the case while checking if the value of pointer points to any valid index or not(I mean to say checking if the memory demanded using memory allocation functions points to a NULL terminator), checking the maximum index of a string and all such codes which may lead to run time error or termination of execution of the program.

This answer is:
User Avatar

User Avatar

Wiki User

11y ago

With the help of Try, Catch and Throw Block..

This answer is:
User Avatar

Add your answer:

Earn +20 pts
Q: Can you describe how Exception Handling is implemented in C plus plus?
Write your answer...
Submit
Still have questions?
magnify glass
imp
Continue Learning about Engineering

What are the Merits and demerits of exception handling in c plus plus?

Are mala cha pahije disadvantages.. ani tumhi mala vichartat.. ask to scientist....


Write a program in c plus plus to call a function and function has essentional exception handling statements?

#include&lt;iostream&gt; extern void handle_eptr (std::exception_ptr eptr) { try { if (eptr) std::rethrow_exception (eptr); } catch (const std::exception&amp; e) { std::cerr &lt;&lt; "Unhandled exception: " &lt;&lt; e.what() &lt;&lt; "\n"; } } void bar() { // Throw "invalid string position" exception. std::string().at(1); } void foo() { try { std::cout &lt;&lt; "Calling bar() from foo():\n"; bar(); } catch (const std::exception&amp; e) { std::cerr &lt;&lt; "Exception in foo(): " &lt;&lt; e.what() &lt;&lt; "\n"; } } int main() { try { std::cout &lt;&lt; "Calling foo() from main():\n"; foo(); std::cout &lt;&lt; "Calling bar() from main():\n"; bar(); } catch (...) // catch all exceptions... { handle_eptr (std::current_exception()); } }


What is the difference between Typedef and Reference in C plus plus?

A typedef is a compiler macro. A reference is a pointer, usually implemented with transparent syntax. They have no relationship between each other.


Do you have a Schematic for power amp model Mt 125?

There are schematics available on the web for about $30 plus shipping and handling.


Can anyone provide me with a C plus plus coding for hotel reservation system using data file handling?

That cannot be answered here; there are commercial packages to do this, which you can locate on the Internet.

Related questions

What is exception handling in C plus plus?

Exception handling is the means by which exceptions -- anomalous events -- are resolved without causing a runtime error.


Which compiler is used for writing c plus plus exception handling programs?

C++ compiler, obviously, a C compiler won't do.


What are the Merits and demerits of exception handling in c plus plus?

Are mala cha pahije disadvantages.. ani tumhi mala vichartat.. ask to scientist....


How exception handling differs in C plus plus and Java?

Exception handling is largely the same for both. The only real difference is that C++ has no 'finally' clause which always executes whether an exception occurs or not. Another difference is that Java throws exceptions and errors, but errors cannot be handled since programs cannot handle errors -- such as the JVM out of memory error.


What is mapping exception in c plus plus?

There is no such exception in C++. It's probably a 3rd party or user-defined exception. Examine the call-stack to determine where the exception was caught -- that should help you determine where the exception was thrown.


Who designed and implemented the c plus plus programming language?

Bjarne Stroustroup


How much does shipping and handling cost for a pillow pet?

$19.95 plus $5.95 shipping and handling


What file pointers are available to support file handling in c plus plus?

For file handling, use the input/output file stream objects, ifstream and ofstream, declared in the &lt;fstream&gt; header of the C++ standard library. Do not use C-style pointers unless you absolutely have to. The problem with "raw" resource pointers is that the resources are not automatically released when the pointers fall from scope. This has implications for exception handling strategies and exceptions are anything but exceptional, particularly where file handling is concerned. When an exception is thrown, every resource consumed between the exception handler and the exception itself must be released. The exception handler is ideally placed in a calling function that is best able to deal with the exception, thus the handler may not have access to the resources that were consumed up to the point the exception occurred. This means that every callee that consumes a resource must include its own localised exception handler which simply releases the resource and re-throws the exception. With resource handles (also known as smart pointers) we do not have this problem because resources are automatically released when the handle falls from scope. Thus our exception handling strategy becomes much more localised and our code becomes that much easier to maintain. And we get all this at no additional cost. Pointers may well give programmers a high-degree of control over resources, but that control has a cost in terms of maintainability and, in some cases, may actually result in reduced performance due to increased code size. Pointers certainly have their uses in C++, but resource management is not one of them. Always use resource handles unless you have good reason not to. In short, C-style resource pointers should only be used in C code, never in C++ code.


How old are you answer person?

I am not 60 and something. I am 59 plus handling and packaging.


What is the cost of electronic shopping?

normal prices plus shipping and handling


How much does Pokemon White cost?

$35.99 (plus tax and shipping and handling


Write a program in c plus plus to call a function and function has essentional exception handling statements?

#include&lt;iostream&gt; extern void handle_eptr (std::exception_ptr eptr) { try { if (eptr) std::rethrow_exception (eptr); } catch (const std::exception&amp; e) { std::cerr &lt;&lt; "Unhandled exception: " &lt;&lt; e.what() &lt;&lt; "\n"; } } void bar() { // Throw "invalid string position" exception. std::string().at(1); } void foo() { try { std::cout &lt;&lt; "Calling bar() from foo():\n"; bar(); } catch (const std::exception&amp; e) { std::cerr &lt;&lt; "Exception in foo(): " &lt;&lt; e.what() &lt;&lt; "\n"; } } int main() { try { std::cout &lt;&lt; "Calling foo() from main():\n"; foo(); std::cout &lt;&lt; "Calling bar() from main():\n"; bar(); } catch (...) // catch all exceptions... { handle_eptr (std::current_exception()); } }