Python Exceptions

It’s important to have a way to handle errors.

Python gives us exception handling.

If you wrap lines of code into a try: block:

try:
    # some lines of code

If an error occurs, Python will alert you and you can determine which kind of error occurred using a except blocks:

try:
    # some lines of code
except <ERROR1>:
    # handler <ERROR1>
except <ERROR2>:
    # handler <ERROR2>

To catch all exceptions you can use except without any error type:

try:
    # some lines of code
except <ERROR1>:
    # handler <ERROR1>
except:
    # catch all other exceptions

The else block is ran if no exceptions were found:

try:
    # some lines of code
except <ERROR1>:
    # handler <ERROR1>
except <ERROR2>:
    # handler <ERROR2>
else:
    # no exceptions were raised, the code ran successfully

A finally block lets you perform some operation in any case, regardless if an error occurred or not

try:
    # some lines of code
except <ERROR1>:
    # handler <ERROR1>
except <ERROR2>:
    # handler <ERROR2>
else:
    # no exceptions were raised, the code ran successfully
finally:
    # do something in any case

The specific error that’s going to occur depends on the operation you’re performing.

For example if you are reading a file, you might get an EOFError. If you divide a number by zero you will get a ZeroDivisionError. If you have a type conversion issue you might get a TypeError.

Try this code:

result = 2 / 0
print(result)

The program will terminate with an error

Traceback (most recent call last):
  File "main.py", line 1, in <module>
    result = 2 / 0
ZeroDivisionError: division by zero

and the lines of code after the error will not be executed.

Adding that operation in a try: block lets us recover gracefully and move on with the program:

try:
    result = 2 / 0
except ZeroDivisionError:
    print('Cannot divide by zero!')
finally:
    result = 1

print(result) # 1

You can raise exceptions in your own code, too, using the raise statement:

raise Exception('An error occurred!')

This raises a general exception, and you can intercept it using:

try:
    raise Exception('An error occurred!')
except Exception as error:
    print(error)

You can also define your own exception class, extending from Exception:

class DogNotFoundException(Exception):
    pass

pass here means “nothing” and we must use it when we define a class without methods, or a function without code, too.

try:
    raise DogNotFoundException()
except DogNotFoundException:
    print('Dog not found!')


This content originally appeared on flaviocopes.com and was authored by flaviocopes.com

It’s important to have a way to handle errors.

Python gives us exception handling.

If you wrap lines of code into a try: block:

try:
    # some lines of code

If an error occurs, Python will alert you and you can determine which kind of error occurred using a except blocks:

try:
    # some lines of code
except <ERROR1>:
    # handler <ERROR1>
except <ERROR2>:
    # handler <ERROR2>

To catch all exceptions you can use except without any error type:

try:
    # some lines of code
except <ERROR1>:
    # handler <ERROR1>
except:
    # catch all other exceptions

The else block is ran if no exceptions were found:

try:
    # some lines of code
except <ERROR1>:
    # handler <ERROR1>
except <ERROR2>:
    # handler <ERROR2>
else:
    # no exceptions were raised, the code ran successfully

A finally block lets you perform some operation in any case, regardless if an error occurred or not

try:
    # some lines of code
except <ERROR1>:
    # handler <ERROR1>
except <ERROR2>:
    # handler <ERROR2>
else:
    # no exceptions were raised, the code ran successfully
finally:
    # do something in any case

The specific error that’s going to occur depends on the operation you’re performing.

For example if you are reading a file, you might get an EOFError. If you divide a number by zero you will get a ZeroDivisionError. If you have a type conversion issue you might get a TypeError.

Try this code:

result = 2 / 0
print(result)

The program will terminate with an error

Traceback (most recent call last):
  File "main.py", line 1, in <module>
    result = 2 / 0
ZeroDivisionError: division by zero

and the lines of code after the error will not be executed.

Adding that operation in a try: block lets us recover gracefully and move on with the program:

try:
    result = 2 / 0
except ZeroDivisionError:
    print('Cannot divide by zero!')
finally:
    result = 1

print(result) # 1

You can raise exceptions in your own code, too, using the raise statement:

raise Exception('An error occurred!')

This raises a general exception, and you can intercept it using:

try:
    raise Exception('An error occurred!')
except Exception as error:
    print(error)

You can also define your own exception class, extending from Exception:

class DogNotFoundException(Exception):
    pass

pass here means “nothing” and we must use it when we define a class without methods, or a function without code, too.

try:
    raise DogNotFoundException()
except DogNotFoundException:
    print('Dog not found!')


This content originally appeared on flaviocopes.com and was authored by flaviocopes.com


Print Share Comment Cite Upload Translate Updates
APA

flaviocopes.com | Sciencx (2021-01-26T05:00:00+00:00) Python Exceptions. Retrieved from https://www.scien.cx/2021/01/26/python-exceptions/

MLA
" » Python Exceptions." flaviocopes.com | Sciencx - Tuesday January 26, 2021, https://www.scien.cx/2021/01/26/python-exceptions/
HARVARD
flaviocopes.com | Sciencx Tuesday January 26, 2021 » Python Exceptions., viewed ,<https://www.scien.cx/2021/01/26/python-exceptions/>
VANCOUVER
flaviocopes.com | Sciencx - » Python Exceptions. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/01/26/python-exceptions/
CHICAGO
" » Python Exceptions." flaviocopes.com | Sciencx - Accessed . https://www.scien.cx/2021/01/26/python-exceptions/
IEEE
" » Python Exceptions." flaviocopes.com | Sciencx [Online]. Available: https://www.scien.cx/2021/01/26/python-exceptions/. [Accessed: ]
rf:citation
» Python Exceptions | flaviocopes.com | Sciencx | https://www.scien.cx/2021/01/26/python-exceptions/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.