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.

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

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.

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

⇐ Go to Python Lesson 4.1 – Exceptions

Go to Python Lesson 4.3  – Finally ⇒

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.