handle error in called class or...

H

hansiman

I'm unsure how best to handle errors in the scenario below!

Say I have a class Employee that handles everything about employees.
The class has two properties "id" and "name", and on procedure
"create" that simply inserts a new employee into the database.

Any error I'd like to show to the user. But how do I make an error
that occurs in the class display in the code that calls the class?

Should I have try catch in both the class (wrapping the ado code) and
in the calling code (wrapping the Employee.Create)?
 
E

Eliyahu Goldin

Catching exceptions in both places makes sense if you want to supply your
own messages. In the class, when you get the exception, you know exact place
in the code when it occurs and can make a message like "Can't insert the new
employee into the database" or "Can't open the database". In the calling
class you catch this custom-made message and communicate it to the user.

Eliyahu
 
H

hansiman

I see. thanks for you answer.

So in my class I would:

class x

private ...
properties...

public sub create()
try
insert into database
catch ex as exception
log error
end try
end sub
end class

and in my code I would:

dim ox as new x
ox.name= "new name"
try
ox.create()
catch ex as exception
display error message
end try

or must I access the exception in my code differently?


/M
 
H

hansiman

So after catching and logging the original exception in the class I
should throw a new error that then would be catchable in the calling
try catch block?
 
E

Eliyahu Goldin

The only comment is you should make sure the exception you catch in the
class will get to the caller. This means you have to throw your own
exception in the catch block in the class.

Eliyahu
 
E

Eliyahu Goldin

yes

Eliyahu

hansiman said:
So after catching and logging the original exception in the class I
should throw a new error that then would be catchable in the calling
try catch block?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,020
Latest member
GenesisGai

Latest Threads

Top