Need "Try" clause to catch database connection error

  • Thread starter Thread starter bill salkin
  • Start date Start date
B

bill salkin

I setup a "Try..." block and attempted to open a non-
existant database. It went to the second "catch" not the
first. What is the proper "catch" clause for this specific
case?

TIA,

Bill


try
conn.open ' will generate an error
....

Catch ex As InvalidOperationException
...
Catch ex As Exception

end try
 
SqlException, I think. From MSDN:
Exception Type Condition
InvalidOperationException Cannot open a connection without specifying
a data source or server.
or

The connection is already open.

SqlException A connection-level error occurred while opening the
connection.
 
bill salkin said:
I setup a "Try..." block and attempted to open a non-
existant database. It went to the second "catch" not the
first. What is the proper "catch" clause for this specific
case?

TIA,

Bill


try
conn.open ' will generate an error
...

Catch ex As InvalidOperationException
..
Catch ex As Exception

end try


Why not have a look at the caught exception?

The docs for the open method say that an OleDBException is thrown.
 
Bill,
It depends on the type of object conn is!

For example according to MSDN OdbcConnection.Open will throw either an
InvalidOperationException or an OdbcException. While SqlConnection.Open will
throw either an InvalidOperationException or an SqlException.

What I normally do is debug it during development then check what type of
exception "Catch ex As Exception" actually caught. I then modify my program
to catch that specific type.

Hope this helps
Jay
 
* "bill salkin said:
I setup a "Try..." block and attempted to open a non-
existant database. It went to the second "catch" not the
first. What is the proper "catch" clause for this specific
case? [...]
try
conn.open ' will generate an error
...

Catch ex As InvalidOperationException
..
Catch ex As Exception

end try

Have a look at the documentation for the connection's 'Open' method you
use ('OleDbConnection', 'SqlConnection', OdbcConnection, ...).

The docs say:

'OleDbConnection'

'InvalidOperationException' if connection already open,
'OleDbException' for errors in the connection level.

'SqlConnection'

See: <http://msdn.microsoft.com/library/e...mdatasqlclientsqlconnectionclassopentopic.asp>

'OdbcConnection'

See: <http://msdn.microsoft.com/library/e...ystemdataodbcodbcconnectionclassopentopic.asp>
 
Jay,

You wrote

"What I normally do is debug it during development then
check what type of exception "Catch ex As Exception"
actually caught."

HOw do you check the exception type?

TIA,

Bill
 
Bill,
HOw do you check the exception type?
Any one of the watch windows (Autos, Locals, Watch 1 thru 4).

The type column will give you the actual type of the ex object, not just the
type of the variable.

Hope this helps
Jay
 
Back
Top