I'm not sure if "throw errors to other classes" is correct to describe my question.
The example is as follows.There're two classes:
A
is a class that being used as adirectory
, just like a directory in the system. It has two private values callfile
anddirectory
. It has a public function calledmkdir
, which will make a directory.It'll throw errors ifdirname
(what tomkdir
) already exists.B
is a class that being used ascommand
, which also has a function calledmkdir
function.mkdir
inB
accepts two parameters: pointer toA
anddirname
.
How should I throw an error in A
and then catch it in B
?
I searched some websites but they only had instructions for throw in functions.
Thanks!
Update 1:
At first I tried to write a bool function called isExist
in A
, and use it in B
before mkdir
. If isExist = true, throw errors(..);
What I'm trying to do here is to regard A
as an object, and itself should throw an error if possible.
code:
class A{
private:
file f;
directory d;
public:
void mkdir(const string& dirname);
}
class B {
private:
shared_ptr<A> p;
public:
void mkdir(shared_ptr<A>, const string&);
}
Update 2:
Ty guys for your answers, I'm much clearer right now. Here're a few useful comments provided @ molbdnilo by in case someone like me are also confused about exceptions.
I'll try to be clearer: If B::mkdir calls A::mkdir, it can catch exceptions that A::mkdir throws. If something else calls A::mkdir, B::mkdir can't notice anything at all. Exceptions have absolutely nothing to do with classes, they only concern the execution of functions. Exceptions work the same regardless of whether the function is a member of a class or not.
Besides, @el.pescado also lists a nice answer.