try-catch summary

Sorry for asking so frequently as I got final exam this monday...

Pls correct me if I am wrong when I say:

try {

throw ...
}

catch (param){//code}

1) throw can be used to throw following:

a) constant value which can be passed to catch param
b) variable which can also be passed to catch param??
c) data type which can be passed to catch param

2) how is it different to use throw only, without try catch statements?
1) You should throw variable. You cannot throw abstract type. So (c) is incorrect

2) In your case thrown exception will be immediately catched and handled. Without catch block it would propagate unwinding call stack until caught (or not).
In fact shown usage is often a sign of bad style: if you can handle problem in place, handle it in place, no need for exceptions.

what about

class dividebyzero{

private:
char*msg;
public:

dividebyzero(char* text):msg(text){}

print(){
cout<<msg<<endl;

}
}

//main

try {
if(b==0)
throw dividebyzero //throwing a type

}
//btw is this syntax ok?
catch(dividebyzero div){

cout<<div.print()<<endl;

}
Last edited on
throw dividebyzero //throwing a type
This stntax is incorrect. You could write throw dividebyzero() where you would throw default constructed variable of type dividebyzero (if you would provide default constructor for it.)

Also whole statement smells.

Why do you even throw anything here? Why not
1
2
if(b==0)
    cout<<div.print()<<endl;
It would do the same with less work.
thats the example I saw but its clear btw, ...
Last edited on
Topic archived. No new replies allowed.