16.7. Exception Recap
try
- block of code that may raise exceptionexcept
- block of code that handles exceptionelse
- block of code that is executed when no exception occurredfinally
- block of code that is executed always (even if there was exception)try
is required and then one of the others blocks
>>> def login(username, password):
... raise PermissionError('Cannot login')
>>>
>>>
>>> try:
... login('alice', 'secret')
... except PermissionError:
... print('Permission error')
... except (ConnectionRefusedError, ConnectionAbortedError) as err:
... print(f'Connection error: {err}')
... else:
... print('Login successful')
... finally:
... print('Disconnect')
...
Permission error
Disconnect
16.7.1. Use Case - 1
>>> def database_connect():
... print('Connecting...')
>>>
>>>
>>> try:
... db = database_connect()
... except ConnectionError:
... print('Sorry, no internet connection')
... except PermissionError:
... print('Sorry, permission denied')
... except Exception:
... print('Sorry, unknown error')
... else:
... print('Connection established')
... print('Executing query...')
... finally:
... print('Disconnect from database')
...
Connecting...
Connection established
Executing query...
Disconnect from database
16.7.2. Use Case - 2
>>> try:
... with open('/tmp/myfile.txt') as file:
... print(file.read())
... except FileNotFoundError:
... print('File does not exist')
... except PermissionError:
... print('Permission denied')
...
File does not exist
16.7.3. Use Case - 3
One cannot simply kill program with Ctrl-C
:
>>>
... while True:
... try:
... number = float(input('Type number: '))
... except:
... continue
One can kill program with Ctrl-C
:
>>>
... while True:
... try:
... number = float(input('Type number: '))
... except Exception:
... continue
Proper way to handle this situation:
>>>
... while True:
... try:
... number = float(input('Type number: '))
... except ValueError:
... continue