Python TutorialLesson 32Free preview
Python Try...Except
This lesson is part of Python · All levels
Summary
The try/except block is used to handle an error (exception) so that the program stays running when a problem occurs. The code at risk fails to be placed on the try block, and the handle is written on the except block. Python also provides another block that runs when there are no errors, and finally that always runs no matter the outcome.
Key points
- The try block contains code that could potentially lead to an exception.
- The except block should specify the type of exception that is dealt with, for example except ValueError.
- Some types of exceptions can be dealt with simultaneously with except (ValueError, TypeError):.
- The block finally always executes, suitable for clearing the resource like closing the file.
Full lesson
Code examples and quizzes
Full lessons, code examples, and quizzes are available to subscribers. 5 questions.