Handling exceptions

S

Sweetiecakes

Hello

I'm a bit confused on how one should handle exceptions. I'm currently
building an ADO.NET Windows Forms application. I've built a class for
manipulating data within the database in question. This class is used
from forms. Let's assume that there is an SQL error: this will throw an
exception. Where should I handle it? How should I handle it? What to
show when giving an error message?

Is there any "centralized" way of handling exceptions: for example,
having a centralized exception handler catch everything, and show an
error message relative to the caught exception?

Thanks
 
B

Bela Istok

Ok this is a multi answer question because there is no a right way to handle
all the exceptions, one that works for me is:
First if the Exception is an expected exception handle that near the code
that gives the Exception.
Second if you can recover from the exception do it near when it's throwing.
If you don't know or expect the exception and because you are using windows
form you can set a Global exception handler in the application object like
this:
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.Automatic);
Application.ThreadException += new
System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
static void Application_ThreadException(object sender,
System.Threading.ThreadExceptionEventArgs e)
{
//Handle here an Unhandled Exception
}

And there you will handle an unexpected exception, but there is a catch, you
need to know if the application can continue after the exception or not.

Regards,

Bela Istok
 
C

Cor Ligthert[MVP]

SweetieCakes,

A very retro question you ask, I think from about the 70's.

But you can of course make a method that handles those in a kind of general
way and pass the exception.

I don't know if it was just speaking words, but an SQL exception should only
be in design time, because it catches the errors you have made in your
scripts.


Cor
 
J

Jeroen Mostert

Cor said:
I don't know if it was just speaking words, but an SQL exception should
only be in design time, because it catches the errors you have made in
your scripts.
I'm in your server room *right now*, unplugging your network. Let's see how
your users like cryptic error messages. :)
 
J

Jon Skeet [C# MVP]

Cor Ligthert said:
A very retro question you ask, I think from about the 70's.

But you can of course make a method that handles those in a kind of general
way and pass the exception.

I don't know if it was just speaking words, but an SQL exception should only
be in design time, because it catches the errors you have made in your
scripts.

And of course nothing *ever* goes wrong with valid SQL... The database
never goes down, there are never concurrency violations, locking
problems, failing to find expected data etc.

There are plenty of reasons why you may see SQL exceptions at execution
time.
 
B

Bela Istok

Nice post sloan, but this is the opposite site of the question. The Cwalina
post talks about throwing exceptions not handling the exceptions. But it's
good to know that too.

Regards,

Bela Istok
 
S

sloan

Most times, you will write

try
{}
finally
{}

blocks. notice no "catch". You don't catch them.





Then, in your presentation layer, you can catch them.

try
{

}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
//Response.Write(ex.Message); //asp.net

}


There's one more tactic. When you want to catch a dotNet, un-user friendly
exception, and make it into something nicer.

This might be in the BAL layer.

try
{
//try something against the db ........
}
catch ( SqlException sqlex )
{
throw new MyCustomDatabaseIsDownException( "Sorry, the db is currently not
working" , sqlex );
}
catch (Exception ex)
{
throw new MyCustomNonHandledException ("Something unexpected happened."
, ex);
}


Its usually a good practice to take the "real" exception and make it the
".InnerException"...when you create your own exception classes. Which you
can handle with the overloaded constructor.

Most times I don't wrap 'em up for the user nice-like. But that's me.
Depending on the audience and application, you might want to wrap 'em up
nice-like.


............
 
C

Cor Ligthert[MVP]

Jon,
And of course nothing *ever* goes wrong with valid SQL... The database
never goes down, there are never concurrency violations, locking
problems, failing to find expected data etc.
As far as I know them will the SQLException ignore all of those problems you
are showing

The SQLexception is needed to check if a stored procedure or an parameter in
that does not exist.
But you are in my opinion a jerk of a developer as you are testing that at
run time.

Cor
 
J

Jeroen Mostert

Cor said:
Jon,

As far as I know them will the SQLException ignore all of those problems
you are showing
Why are you second-guessing this with "as far as I know"? Wouldn't you at
least like to try it first before simply reasserting what someone else has
drawn into question?

An SqlException will be raised for *any* critical error signaled by the
database, including lock timeouts, I/O errors, wrong logins and plain and
simple unreachability of the database, none of which are predictable by the
application developer. I know this because I've seen it. Can you say you've
seen the opposite?

There *are* some errors that are not translated to an SqlException, and it's
also true that some SqlExceptions are not raised until you've read all the
result sets, but it's definitely not true that any SqlException can be
predicted at design time.
The SQLexception is needed to check if a stored procedure or an
parameter in that does not exist.
But you are in my opinion a jerk of a developer as you are testing that
at run time.
Since the facts you base your opinion on are wrong, that doesn't mean much.
 
J

Jon Skeet [C# MVP]

Cor Ligthert said:
As far as I know them will the SQLException ignore all of those problems you
are showing
Nope.

The SQLexception is needed to check if a stored procedure or an parameter in
that does not exist.

Nope.

From the docs:

<quote>
This class is created whenever the .NET Framework Data Provider for SQL
Server encounters an error generated from the server.
</quote>

There are plenty of errors which a database can encounter at execution
time beyond just whether or not your SQL is valid and calling valid
stored procs with the right number of parameters.
 
A

Arne Vajhøj

Cor said:
Jon,
As far as I know them will the SQLException ignore all of those problems
you are showing

The SQLexception is needed to check if a stored procedure or an
parameter in that does not exist.
But you are in my opinion a jerk of a developer as you are testing that
at run time.

No.

ADO.NET does not return status values.

Either it is a success all the way through or you get an
exception.

The only bad thing about the exception is that you get the
same exception type for too many different problems. I guess
that will be fixed in .NET 4.0 or 5.0 !

Arne
 
C

Cor Ligthert[MVP]

Jeroen,

You give your own answer, the SQLException is about errors raised at Server
side. Which I as I have them, seriously evaluate the program before I give
them to the users, because those are in my opinion all design time errors
(including the environment), I never have lock errors as I use never any
more the old fashion way of setting lock bits, which is not based on modern
processing with 1000 users online anymore.

The rest of the errors which you give are by the way as well catched at
client side with the normal exception, which I forever use and before that
and try before processing if the database is online with a normal exception
to check if the connection is correct.

However, feel free to do it your way.

Cor
 
C

Cor Ligthert[MVP]

Jon,

Buy a book about AdoNet and try to understand what is Server side and what
is Client side in that.

Cor
 
C

Cor Ligthert[MVP]

Arne,

Can you point me where your answer is about. I don't have the idea to have
written anything about a Status.

But what you wrote is in my opinion true, although you can catch with the
SQLException some information why the SQL transaction on the Server Side
went wrong. However, in my opinion a designer should fix all those errors
which are catched here fix before he gives his program in production. (Or
catch them at client side as it is hardware dependend, I have never seen a
server, which was down, give any information)

http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlexception.aspx

Cor
 
J

Jon Skeet [C# MVP]

Buy a book about AdoNet and try to understand what is Server side and what
is Client side in that.

I don't need to buy a book to know that things can go wrong in a
database beyond SQL validation errors, and when those things happen,
you get a SQL exception.

I suggest you try writing an application which constantly accessed a
database, and shut the database down while it's running. See what
happens.

Jon
 
J

Jeroen Mostert

Cor said:
You give your own answer, the SQLException is about errors raised at
Server side. Which I as I have them, seriously evaluate the program
before I give them to the users, because those are in my opinion all
design time errors (including the environment),

How is a broken network connection a design time error? *Handling* the
broken network connection is a design-time issue. A program cannot predict,
prevent or flawlessly detect a broken network connection, no matter how hard
it tries. Sometimes things just go wrong as you're doing them. Signaling
that we unexpectedly cannot complete an operation is what exceptions are
*for*. Stress "unexpectedly".
I never have lock errors as I use never any more the old fashion way of
setting lock bits, which is not based on modern processing with 1000
users online anymore.
Locking is a cornerstone of most implementations of ACID, and I'm not
talking about explicit client-side locking. But let's move on, this is a
side issue.
The rest of the errors which you give are by the way as well catched at
client side with the normal exception, which I forever use and before
that and try before processing if the database is online with a normal
exception to check if the connection is correct.
What on earth is "catching with the normal exception"? Do you mean a
catch-all exception handler for "things went wrong"?
However, feel free to do it your way.
We have in no way, shape or form entered the realm of personal preference in
this discussion. The issues mentioned here are going to be part of every
error-handling strategy, and I haven't said anything about how such a
strategy should look. Asynchronous exceptions while accessing a database
server are a simple fact of life. It is the very nature of these exceptions
that no amount of design-time cleverness will eliminate them.

I strongly get the feeling that we're talking about completely different
thigns without realizing it.
 
A

Arne Vajhøj

Cor said:
Can you point me where your answer is about. I don't have the idea to
have written anything about a Status.

There are only two alternatives for returning errors: exceptions and
status codes. So since .NET does not have status codes, then the
choices are somewhat limited-
But what you wrote is in my opinion true, although you can catch with
the SQLException some information why the SQL transaction on the Server
Side went wrong.

You can, but that is very bad OOP.
However, in my opinion a designer should fix all those
errors which are catched here fix before he gives his program in
production.

None of the problems Jon list is permanent problems. They can
happen in production even if they do not happen in test.

And even if the database server did go down under test, then I am not
quite sure what the designer should fix ? Not use a database ??
(Or catch them at client side as it is hardware dependend, I
have never seen a server, which was down, give any information)

I am not quite sure what you mean by client and server here, but
since it is about database access let us assume database client
and server.

If the database server si down, then the database client will
get an exception and need to handle it. Like Jon explained.

Arne
 
A

Arne Vajhøj

Cor said:
You give your own answer, the SQLException is about errors raised at
Server side. Which I as I have them, seriously evaluate the program
before I give them to the users, because those are in my opinion all
design time errors (including the environment), I never have lock errors
as I use never any more the old fashion way of setting lock bits, which
is not based on modern processing with 1000 users online anymore.

It is completely impossible to find all problems that could happen
with a database server.

There is a reason that clustering is used if uptime is needed.
The rest of the errors which you give are by the way as well catched at
client side with the normal exception, which I forever use and before
that and try before processing if the database is online with a normal
exception to check if the connection is correct.

Oh - if the database is working when you start then it will continue
to work ?

Do you have that in writing from MS ??

Arne
 

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

Top