Python Lessons – 4.2 Exception Handling

Python Lessons - 4.2 Exception Handling

Exception Handling

In the previous section you saw that when the code execution encounters an error, an exception is generated that interrupts the execution of the program. To avoid this you can handle the exception, so as to correct the error, have the possibility to remedy or provide output information on the nature of the error occurred in order then to understand its nature and correct the code.

In Python, you can handle an exception through the try-except construct.

try :
blocco try
except NomeErrore:
blocco except

The try clause defines the block of code in which an exception could be thrown. If the exception occurs, the execution of the statements inside the try block is interrupted and it should be checked whether this exception is handled via the except clause. If the exception name is present (so it is managed) then the corresponding except block code is executed.

a = 5
b = input("Insert a number: ")
try:
    b = int(b)
    res = a/b
    print("5 / ",b," = ",res)
except ZeroDivisionError:
    print("Be aware, you are asking a division by zero") 

By executing the code and entering the value 0, you will get the message instead of an error.

>>>
Inserisci un valore numerico: 0
Attenzione stai effettuando una divisione per zero

Now, however, if instead of entering a numerical value, inserting a character or a string, it would be a ValueError exception. Well, this possibility can also be managed by extending the previous code with a further clause and block except.

a = 5
b = input("Inserisci un valore numerico: ")
try:
    b = int(b)
    res = a/b
    print("5 / ",b," = ",res)
except ZeroDivisionError:
    print("Attenzione stai effettuando una divisione per zero")
except ValueError:
    print("Attenzione hai immesso un valore errato") 

This time, running the code and inserting a string, for example, correctly handles the exception.

>>>
Inserisci un valore numerico: lkj
Attenzione hai inserito un valore errato

⇐ Go to Python Lesson 4.1 – Exceptions

Go to Python Lesson 4.3  – Finally ⇒

Leave a Reply