[Tutor] Catching different exceptions

mikalzet@libero.it mikalzet@libero.it
Tue, 12 Feb 2002 16:21:25 +0100 (CET)


If I do:

import pgdb
import os
db = pgdb.connect(host = 'localhost', user = 'myname', passwd =
'mypasswd', database = 'turni')

different things can happen:

1) the database exists and the connection works (which means the program
has already been run at least once ... interesting ... whatever weird
name I choose it is always possible for a database with the same name to
have been created on my system already by some other program ... don't
think this type of error can be caught can it ?);
2) the database exists but the connection doesn't work (wrong passwd,
username or whatever) ....
3) the database does not exist, I get the following error message:
_pg.error: FATAL 1: Database "turni" does not exist in the system catalog
........ which is right and proper.

I can try to catch some exceptions like this:

try:
	db = dbpg.connect(database = 'turni')
except:
	os.system('createdb turni')

This last can fail for various reasons:
1) I am not authorized to create new databases, in this case I need an
error message telling me to contact my postgres administrator so that he
can create it for me;
2) I am not an authorized user of postgres at all, so I need a different
error message;
3) postgres doesn't exist on my system.

How do I tell python how to distinguish between different types of
exceptions ?

Is it something like:

try:
	foo
except(fooerror1):
	foo1
except(fooerror2):
	foo2
except(fooerror3):
	try:
		foo4
	except(fooerror4):
		foowhatever

Or is it possible for me to test for the existence of a working
postgres setup, a correct database and table directly, leaving exception
handling to take care of subtler errors ?

-- 
Michele Alzetta