Basis for Exception Handling
Even if you create a program that has no errors in syntax, errors
can occur during execution. Errors that occur during the execution of a program
are called “exceptions”. Since it is not possible to take into account all of
the circumstances that might occur during the execution, even when errors
occur, the program must have special equipment to be able to operate normally.
It is possible to make a program operate safely with exception handling.
The basic structure for exception handling is as follows.
try: #(1) Program
with Errors #(2) except Exception type: #(3) Exception
Handling else: #(4) Normal
Processing finally: #(5) Unconditionally
executed, irrespective of the occurrence of the exception |
(1) Start: Exception handling is started by
using the reserved word “try”.
(2) Program
with Errors: An error may occur during program execution.
(3) Exception
Handling: Specify the type of exception that is to be handled. Multiple
exception types can be specified, and when it is not clear what kind of exception
can occur, it can be omitted.
(4) Normal Processing: If an exception does
not occur, the “else” statement can be omitted.
(5) Unconditional
Execution: This will be executed unconditionally, irrespective of the
occurrence of the exception. The “finally” statement can be omitted.
Exception Handling
This
simple example can be used to learn about the behavior to handle exceptions.
Here, a division operation is used to divide by 0 in an attempt to
intentionally generate errors. Let's then make a program for normal operation using
the “try except’ statement.
try: a =
10 / 0 #(1) except: #(2)
print "1.[exception] divided by zero " print "\n"
try: a =
10 / 0
print "value of a: ", a except ZeroDivisionError: #(3)
print "2.[exception] divided by zero "
print "\n"
try: a =
10 b =
"a" c =
a / b except (TypeError, ZeroDivisionError): #(4)
print "3.[exception] type error occurred" else:
print "4.type is proper" #(5) finally:
print "5.end of test program" #(6)
>>> 1.[exception] divided by zero
2.[exception] divided by zero
3.[exception] type error occurred 5.end of test program |
Exception
Handling
(1) An Exception
Occurs: In the middle of executing the division, an exception is generated
by using 0 as the dividend.
(2) Exception
Handling: Exception handling starts without specifying the type of
exception, and an error message is printed.
(3) Indicating
the Type of Exception: Start the exception handling by specifying the type
of exception (ZeroDivisionError)
(4) Explicit Multiple Exceptions: It is
possible to explicitly process multiple exceptions.
(5) Normal Processing: If no exception
occurs, normal processing prints a message.
(6) Unconditional Execution: Regardless of whether or not an exception occurs, the program prints this message.