I was reading my C++ text and it showed me this error scaffolding. However it doesn't explain the "exception& e" part.I know that the & means something is being "passed by reference", but I've never seen the exception datatype.
#include "std_lib_facililies.h"
int main(){
try {
//your code here
keep_window_open();
return 0 ;
}
catch (exception& e) {
cerr << "error: n << e. whatO << '\n ' ;
keep_window_openO:
return 1 ;
}
catch (...) {
cerr « "Oops: unknown exception!\n";
keep_window_open() ;
return 2;
}
}
Related
In which cases do Options 1 and 2 give different results/behaviour?
Are they equivalent in all respects?
I tried with a non-existing in_out/sample2.txt to force an exception and they behave the same.
int main() {
string fnamein2 = "in_out/sample2.txt";
ifstream ifstr;
try {
cout << "Reading " << fnamein2 << endl;
ifstr.open(fnamein2);
ifstr.exceptions( ifstream::eofbit | ifstream::failbit | ifstream::badbit );
} catch(const exception &e) { // <-- Option 1
//} catch(const ifstream::failure &e) { // <-- Option 2
cout << "There was an error: " << e.what() << endl;
}
return 0;
}
There is no difference in your scenario.
std::ifstream::failure is specialized version of std::exception (contains more details) but in your case you do not used them.
std::ifstream::failure has code method which gives you more information about an error. But if you do not need it, you can use base class.
I'm working on a fairly lengthy program, and after running fine for awhile, suddenly I'm getting:
terminate called after throwing an instance of 'std::out_of_range'
what(): basic_string::substr
Being new to exception handling, I did some research and found that I would likely get more information by adding the following to my main function:
int main(int argc, char **argv){
try{
//stuff
}
catch(exception const &exc){
cerr << "Caught exception: " << exc.what() << endl;
}
}
The result of this is the following output:
Caught exception: basic_string::substr
This isn't any more useful than the default output; it doesn't tell me anything about the line triggering the core dump (there are many substr calls in my program), the data the substr is attempting to process, etc. Is there a method for displaying information such as this in C++, or is my only option to use a debugger such as gdb?
There are a few ways.
As you said, a debugger - but that won't help you once the code is in production.
Nested exceptions and function try blocks. e.g.:
#include <exception>
#include <stdexcept>
#include <iostream>
#include <sstream>
#include <iomanip>
void bar(std::string& s, int i)
try
{
s.at(i) = 'A';
}
catch(...)
{
std::ostringstream ss;
ss << "error in bar(" << std::quoted(s) << ", " << i << ")";
std::throw_with_nested(std::runtime_error(ss.str()));
}
void foo(std::string& s)
try
{
bar(s, 6);
}
catch(...)
{
std::ostringstream ss;
ss << "error in foo(" << std::quoted(s) << ")";
std::throw_with_nested(std::runtime_error(ss.str()));
}
void stuff()
try
{
std::string s;
foo(s);
}
catch(...)
{
std::throw_with_nested(std::runtime_error("error in stuff()"));
}
void print_exception(std::ostream& os, const std::exception& e, int level = 0)
{
os << std::string(level, ' ') << "exception: " << e.what() << '\n';
try {
std::rethrow_if_nested(e);
} catch(const std::exception& e) {
print_exception(os, e, level+1);
} catch(...) {}
}
int main()
{
try{
stuff();
}
catch(std::exception& e)
{
print_exception(std::cerr, e);
return 127;
}
return 0;
}
sample output:
exception: error in stuff()
exception: error in foo("")
exception: error in bar("", 6)
exception: basic_string::at: __n (which is 6) >= this->size() (which is 0)
You could use boost::stacktrace in place of the above nested exception handling.
http://coliru.stacked-crooked.com/a/f21bd35632a0a036
Beginner programmer here, working in Visual Studio.
vector<string> fileParse(vector<string> & inputStrings, string & fileName) {
ifstream x;
x.open(fileName);
cout << "attempting to open file" << endl;
if (!x.is_open()) {
cout << "Bad input file name. Input was: " << fileName << endl;
throw lab0badInput;
}
else {
string temp;
while (x >> temp) {
inputStrings.push_back(temp);
}
x.close();
}
return inputStrings;
}
Calling throw causes my program to crash instead of throwing the correct value and exiting. Can somebody explain why?
Thanks!
use try and catch block instead :
try { /* */ } catch (const std::exception& e) { /* */ }
So I've got a program with two exception. In both cases, I'd like to throw a string that can be caught in the main function and used in an error message. However, from what I know about them
try {
...
} catch(string msg) {
cerr << "..." << msg << "..." << endl;
} catch (string msg2) {
cerr << "..." << msg2 << "..." << endl;
}
isn't allowed. Is there any way I could do the above or something like it?
Thanks
I see two use cases:
1. You want two distinct types of errors.
Add exception classes derived from std::exception
class MyException1 : public std::exception
{
std::string message;
public:
MyException1(std::string const &what_arg) : message(what_arg) {}
MyException1(char const * what_arg) : message(what_arg) {}
const char* what() const { return message.c_str(); }
};
class MyException2 : public std::exception
{
std::string message;
public:
MyException2(std::string const &what_arg) : message(what_arg) {}
MyException2(char const * what_arg) : message(what_arg) {}
const char* what() const { return message.c_str(); }
};
and catch those:
try
{
int a = 5;
// do stuff
if (a == 7)
{
throw MyException1("Error 1 occured in because a == 7.");
}
else if (a == 5)
{
throw MyException1("Error 1 occured because a == 5.");
}
// do more stuff
if (a == 22)
{
throw MyException2("Error 2 occured in because a == 22.");
}
else if (a == 575)
{
throw MyException2("Error 2 occured because a == 575.");
}
}
catch (MyException1 &ex)
{
std::cout << "Exception 1: " << ex.what() << "\n";
}
catch (MyException2 &ex)
{
std::cout << "Exception 2: " << ex.what() << "\n";
}
Note: This is an easy but not the best design for a custom exception since std::string may throw and your program will be terminated.
2. You want two different error messages:
Use the appropriate type of exception from <stdexcept> header:
try
{
int a = 5;
// do stuff
if (a == 7)
{
throw std::runtime_error("Error 1 occured because a == 7.");
}
else if (a == 5)
{
throw std::runtime_error("Error 2 occured because a == 5.");
}
}
catch (const std::exception &ex)
{
std::cout << "Exception: " << ex.what() << "\n";
}
Note: The behaviour of case 1 can be emulated in case 2 without own types if the only desired behaviour is different output:
try
{
int a = 5;
// do stuff
if (a == 7)
{
throw std::runtime_error("Exception 1: Error 1 occured in because a == 7.");
}
else if (a == 5)
{
throw std::runtime_error("Exception 1: Error 1 occured because a == 5.");
}
// do more stuff
if (a == 22)
{
throw std::runtime_error("Exception 2: Error 2 occured in because a == 22.");
}
else if (a == 575)
{
throw std::runtime_error("Exception 2: Error 2 occured because a == 575.");
}
}
catch (const std::exception &ex)
{
std::cout << ex.what() << "\n";
}
Use std::runtime_error it has a constructor that takes a string. So pass it a different value when it is throw.
throw runtime_error( "msg1");
...
throw runtime_error("msg2");
Then when you catch just print the message in the object
...
catch( exception& e ){
cout << e.what() << endl;
}
First: Your compiler is supposed to issue a warning for that, because, the second catch will never be executed, because they are of exact signatures. Besides, you cannot have a second exception being thrown while the first is active ( exception thrown during stack unwinding that hasn't entered a catch block yet), else, the runtime will terminate your program.
Secondly: prefer to catch your exceptions by reference
Thirdly: Prefer to have your exception object fall in the inheritance tree of std::exception.
Lastly: What the hell are you trying to do?
IN the below code snippet why is that if I include the catch statement with "exception base class I get a app crash" (attached the image of teh crash).
But if I use
"const char* msg"
in catch() it works fine.
WHy is it that the exception base class is causing teh app crash ?
double division(int a, int b)
{
if (b == 0)
{
throw "Division by zero condition!";
}
return (a / b);
}
main()
{
int x = 50;
int y = 0;
double z = 0;
try {
z = division(x, y);
cout << "after division func" << endl;
cout << z << endl;
}
catch (const char* msg) { // WORKS FINE
//catch (exception& err) { // CAUSES the APP to crash![enter image description here][1]
cout << "INside catch for divide by 0" << endl;
}
Here you are throwing a string literal:
throw "Division by zero condition!";
Which can be caught with the following:
catch (const char* msg)
However this exception does not derive from the class std::exception. If you want one which is and can provide an error message then use std::runtime_error.
throw std::runtime_error("Division by zero condition!");
...
catch (std::exception& err)
Division by zero condition is not derived by std::exception
one workaround you can do is to define catch all statement in you code
try {
z = division(x, y);
cout << "after division func" << endl;
cout << z << endl;
}
catch (exception& err) { // CAUSES the APP to crash![enter image description here][1]
cout << "INside catch for divide by 0" << endl;
}
catch(...) //include this in your code
{
cout<<"other exception occured";
}
See here http://ideone.com/TLukAp