B13_TuHoc_09_Exception Handling
B13_TuHoc_09_Exception Handling
Lê Ngọc Hiếu
[email protected]
Introduction to Python exceptions
• A Python program terminates as soon as it encounters an
error.
• In Python, an error can be a syntax error or an exception
error.
2
Catching Exceptions in Python
• In Python, exceptions can be handled using a try and
exception statement. try:
• Syntax: # statements
.....
• The try block: use to test a block
except
of code for errors.
ExceptionErrorName:
• The except block: use to handle
# statements
the error.
.....
• The else block: defines a block of
else:
code to be executed if no errors
# statements
were raised (This block is
.....
optional).
finally:
• The finally block: to execute
# statements
code, regardless of the result of
..... 3
Catching Exceptions in Python: Example
4
Catching Exceptions in Python: Example
5
Python Built-in Exceptions
Exception Description
ArithmeticError Raised when an error occurs in numeric calculations
AssertionError Raised when an assert statement fails
AttributeError Raised when attribute reference or assignment fails
Exception Base class for all exceptions
UnicodeTranslateErro
Raised when a unicode translation problem occurs
r
Raised when there is a wrong value in a specified
ValueError
data type
ZeroDivisionError Raised when the second operator in a division is zero 9
Many Exceptions
• You can define many
exception blocks.
• Each block of code for a
special kind of error.
10
Many Exceptions
11
Raise an Exception
• We can throw an exception if a condition occurs.
• To throw (or raise) an exception, use the raise keyword.
12
User-Defined Exception
13