answersLogoWhite

0


Best Answer
You mean try and catch. There is no finally in C++; it is not required because RAII (Resource Acquisition Is Initialisation) renders it redundant.
A try block provides the primary means of handling runtime errors in C++:

int main () {
try {
std::string().at(1); // throws!
} catch (const std::exception& e) {
std::cerr << e.what () << std::endl;
}
}


Example output:
invalid string position


A catch block is an exception handler for a given type of exception. Every try block must have at least one catch block but we can have as many catch blocks as required to handle different types of exceptions and deal with each one accordingly. The std::exception class is just one type of exception.

The point at which an error is detected can often be quite far-removed from the point at which the error can be handled. The above example isn't the sort of code you'd find in a real-world application; it's fairly obvious where the problem lies because we deliberately forced an exception to be thrown via the tryblock and the error message is reasonably self-explanatory. But in the real-world we're more likely to see code similar to the following:

int main () {
try {
do_a_task(); // might throw
do_another_task(); // might throw
} catch (const std::exception& e) {
std::cerr << e.what () << std::endl;
}
}



If any exception is thrown there are two possible sources for that error. The more complex those functions are the more difficult it becomes to locate the errant code. Indeed, the error could originate from a deeply-nested series of function calls from within either of these two functions.

However, it is not actually necessary to know where an error occurs in order to handle the error. It is enough to know that the error has been caught. It's the ones we don't catch that we really need to worry about because an unhandled exception will terminate our program without any warning. Worse, whatever message the exception carried with it will be lost forever (we'd need to use a debugger to determine why the program aborted).

Production code will often place a series of specific exception handlers in main(), along with a somewhat convoluted catch-all to try and catch any and all unknown exception types:

int main () {
try {
do_a_task(); // might throw
do_another_task(); // might throw
} catch (const int& i) {
std::cerr << i << " : some idiot threw an integer!" << std::endl;
} catch (const char* s) {
std::cerr << s << std::endl;
} catch (const std::string& s) {
std::cerr << s << std::endl;
} catch (...) {
std::exception_ptr eptr {std::current_exception()};
try {
if (eptr) std::rethrow_exception (eptr);
} catch (const std::exception& e) {
std::cerr << e.what () << std::endl;
} catch (...) {
std::cerr << "unknown exception type" << std::endl;
}
}


Note that catch (...) is the catch-all handler but even this cannot be guaranteed to catch all errors, particularly if we make extensive use of third-party libraries. Programmers that throw meaningless integers instead of well-defined exception classes derived from std::exception are a particular annoyance, because two different libraries might use the same integer value to represent two completely different exceptions. Then there are those who persist in throwing C-style strings or (worse) std::string objects. Then there are those who detest the standard library to such a degree they will re-invent the wheel and throw ad-hoc exception classes into the mix.

Some implementations may provide proprietary methods that will catch any and all exceptions, however the code is not portable.


Some exceptions simply cannot be caught because they are not exceptional. Division by zero is a common example. This is not an exception because any code that allows a divide by zero operation has undefined behaviour. As such, the entire program is invalid and no amount of exception handling will turn an invalid program into a valid one. Note that division is a low-level machine operation, not a high-level function. The only way to prevent a divide by zero error is to not do it. Always check your denominators are non-zero! This is no different to ensuring a pointer is non-null before attempting to dereference it. But if you use smart pointers instead of "naked" pointers you get automatically get all the benefits of exception handling at no cost. Indeed, the fewer runtime tests you perform the more efficient your code will be.
User Avatar

Wiki User

8y ago
This answer is:
User Avatar

Add your answer:

Earn +20 pts
Q: What does try and finally mean in C plus plus programming?
Write your answer...
Submit
Still have questions?
magnify glass
imp
Continue Learning about Engineering

What makes for a good or bad variable name in C plus plus programming languages?

A good variable name is one that is clear, related to the data it stores. Also, you should try to avoid confusions with other variables.


Assembly language programming on mergesort?

try making yourself..hope it will be useful ofr you!


What is finally block in java?

The Finally block in java is used along with the try-catch statements. The usual structure is try { ..... } catch(Exception e){ .... } finally { ..... } In the finally block we usually have code that is used to perform clean up activities corresponding to the code in the try block. When an exception occurs in the try block control comes to the catch block and the rest of the code in the try block would not execute. In such cases we may need to have some code that cleans up the objects that we created/used in the try block. No matter what happens, the code inside the finally block would definitely execute. The best use of finally block is when we are connecting to the database. In the try block we would have the statements that instantiate the connection, prepared statement, result set etc. If the query fails then all these objects would be left open and the code would continue. So in the finally block we usually nullify these statements so that even in case of an error the unused objects are cleared. Example: Connection con; PreparedStatment PS; ResultSet rs; try{ con = ConnectionManager.getConnection(); PS = con.prepareStatement(query); rs = PS.executyQuery(); ...... } catch (Exception e){ e.printStackTrace(); } finally { con.close(); PS.close(); } In case of an error the connection &amp; prepared statement objects would remain open if we do not have the finally block. Tip: Whatever code we have inside the finally block would be run definitely if the try block is invoked. We can even use the finally block to check if the try block was reached and executed. If the try executes then we can rest assured that the finally would also get executed.


How do you execute all statement in try block if an exception occurs?

If you have an exception you should fix mistake in your try block. If you want to run some code even after exception was thrown you can use full form of try block:try{...}catch (...){...}finally{...}Where the statement finally is what you need. Make sure that the code you run within this statement is not able to trow exceptions.


What is finally statement in java?

Although try and catch provide a great way to trap and handle exceptions, we are left with the problem of how to clean up if an exception occurs. Because execution transfers out of the try block as soon as an exception is thrown, we can't put our cleanup code at the bottom of the try block and expect it to be executed if an exception occurs. Exception handlers are a poor place to clean up after the code in the try block because each handler then requires its own copy of the cleanup code. If, for example, you opened a database connection somewhere in the guarded region, each exception handler would have to release the connection. That would make it too easy to forget to do cleanup, and also lead to a lot of redundant code. If you forget to close the connection in cases where an exception occurs, you will be left with orphan connections which can eventually crash your database. To address this problem, Java offers the finally block. A finally block encloses code that is always executed at some point after the try block, whether an exception was thrown or not. Even if there is a return statement in the try block, the finally block executes right after the return statement is encountered, and before the return executes! This is the right place to close your files, release your db connections, and perform any other cleanup your code requires. If the try block executes with no exceptions, the finally block is executed immediately after the try block completes. If there was an exception thrown, the finally block executes immediately after the proper catch block completes. Let's look at another pseudocode example: 1: try { 2: // This is the first line of the "guarded region". 3: } 4: catch(DatabaseDownException) { 5: // Put code here that handles this exception 6: } 7: catch(SomeOtherException) { 8: // Put code here that handles this exception 9: } 10: finally { 11: // Put code here to release any resource we 12: // allocated in the try clause. 13: } 14: 15: // More code here As before, execution starts at the first line of the try block, line 2. If there are no exceptions thrown in the try block, execution transfers to line 11, the first line of the finally block. On the other hand, if a SomeOtherException is thrown while the code in the try block is executing, execution transfers to the first line of that exception handler, line 8 in the catch clause. After all the code in the catch clause is executed, the program moves to line 11, the first line of the finally clause. To summarize - THE FINALLY BLOCK WILL EXECUTE ALWAYS. There is actually a catch here about the finally block executing always, but I will leave you to ponder over it for sometime. We will look at it a little later.

Related questions

How we can install the c and c plus plus?

You cannot 'install' programming languages. Instead, you can try to install a compiler or an IDE.


Why c plus plus is called as oops?

OOP means "object oriented programming" this means that you can make objects instead of C where you use procedural programming (it's advance try to google it :) )


How many finally block can be used for an exception handler?

Genaerally every try block maintain the one finally block or atleast one catch block or both. It mean try { try{ try{ } or } or } finally { catch(....) { catch(...){ } } } catch(.....) { : } finally{ : } Hear whenever we declar the try block without catch or finally bocks it show the compile time error like ' try without catch or finally' and also it is not possible to declare the any statements in between the try ,catch and finally blocks. ex: try{ } System.out.println("statement"); finally { } The above example show the compile time error 'try without catch or finally'. " Hear the finally block must be execute after excuting the try or catch block. Hence the finally block is used to release the resources like closing the streams and closing the jdbc connections." Hence in exception handling we use one finally block for one try block to release the resources.


What are a good programming languages for programming artificial intelligence systems?

LISP is designed for AI programming, give that a try.


What makes for a good or bad variable name in C plus plus programming languages?

A good variable name is one that is clear, related to the data it stores. Also, you should try to avoid confusions with other variables.


I am 42 years old and I have never been in game design and development but I have some knowledge in 3d modeling and C plus plus programming. Can you help?

Start learning 2d game programming. (SDL, Allegro, SFML or something simuler) Then you can try some 3d programming (DirectX or OpenGL are the most known libaries) OpenGL is cross platform and open source so it should be easier to find tutorials to.


Can you program Google on Khan Academy?

No, if you try than Oh noes will pop up. This will happen because Google programming is not the same as Khan Academy plus, Google is copyrighted material.


Is physics appropriate for people who are good at math but not programming?

You don't need computer programming for physics. Try it out; you might like it.


Programming instructions 2005 expedition remote?

Try www.programyourremote.com


What does hypothesis mean science terms?

HYPOTHESIS: a hypothesis is what you think will happen. You should try starting it off with my hypothesis is... next it will.... then it will... finally it will...


What does computer programming mean in general terms?

well .. talking about in general terms (like making some newbie to understand, what the computer programming is about) so we must say that computer programming is like ..Programming a computer to do some task. in programming we create a sequence of instructions that enables the computer to do something.like we try to make the computer understand what we want to do so that it can help us to do that work. or even sometimes the computer can do that task itself and give the desired output.sourabh882008@yahoo.com


Which is equivalent to try and finally block?

Try block is followed by finally block as an alternative . But usually it is followed by a catch block. Both are equivalent.