C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Except: In the except statement, we receive the ZeroDivisionError. And we print a special message.
Note: This program does not terminate because of this exception. We could continue the program after this point.
Python program that uses except statement
try:
x = 1 / 0
except ZeroDivisionError:
print("Tried to divide by zero")
Output
Tried to divide by zero
Traceback: The Python environment helpfully shows a traceback. This contains the methods called. The mistake() call is shown.
Python program that uses raise
def mistake(name):
# Raise an example with custom string.
raise Exception(name + " caused exception")
# Call method.
mistake("Voorheesville")
Output
Traceback (most recent call last):
File "C:\file.py", line 4, in <module>
mistake("Voorheesville")
File "C:\file.py", line 2, in mistake
raise Exception(name + " caused exception")
Exception: Voorheesville caused exception
Here: The "raise" statement the exception not to be captured. The print-statement is executed before the program terminates.
Python program that reraises exception
try:
# This causes an exception.
f = open("abc")
except:
print("Except hit")
# Raise the exception again.
raise
Output
Except hit
Traceback (most recent call last):
File "C:\programs\file.py", line 6, in <module>
f = open("abc")
IOError: [Errno 2] No such file or directory: 'abc'
Tip: In the else, you can perform an action required when no errors are encountered.
Here: We show a while-True infinite loop. We accept input from the console, and parse it with the int() built-in method.
Convert: Int, StringThen: We attempt to divide by the number entered. If zero is entered, the except-block is reached. Otherwise, the else is reached.
Python program that uses try, else
while True:
# Read int from console.
denominator = int(input())
# Use int as denominator.
try:
i = 1 / denominator
except:
print("Error")
else:
print("OK")
Output
1
OK
2
OK
0
Error
Here: An error is raised in the try clause. After the "except" clause is executed, the finally clause runs.
Python program that uses finally
try:
# An error occurs.
x = 1 / 0
except:
# Except clause:
print("Error encountered")
finally:
# Finally clause:
print("Finally clause reached")
Output
Error encountered
Finally clause reached
Python program that uses as, except
try:
f = open("does-not-exist")
except IOError as err:
# We can use IOError as an instance.
print("Error:", err)
print("Number:", err.errno)
Output
Error: [Errno 2] No such file or directory: 'does-not-exist'
Number: 2
Here: The "outer" method causes a terrifying ZeroDivisionError. We see the inner() method too in the Traceback.
Lines: The Traceback helpfully provides line numbers to aid in our debugging efforts.
Python program that shows traceback output
def outer(n):
return 100 / n
def inner(n):
return outer(n)
# This causes an error.
# ... Python provides a stack trace that shows the call stack.
inner(0)
Output
Traceback (most recent call last):
File "C:\programs\file.py", line 12, in <module>
inner(0)
File "C:\programs\file.py", line 8, in inner
return outer(n)
File "C:\programs\file.py", line 5, in outer
return 100 / n
ZeroDivisionError: division by zero
Version 1: In this loop, the code causes a ZeroDivisionError on each iteration.
Version 2: In this version of the code, we test against zero with an if-statement, and no exception is raised.
IfResult: The loop body that uses exception-handling is much slower. The exception is raised on each iteration through the loop.
WhileTip: Avoiding exceptions, as by checking a denominator against zero, often leads to performance advantages.
Python program that times exceptions
import time
print(time.time())
# Version 1: cause exception.
v = 0
i = 0
while i < 10000000:
try:
x = 10 / v
except ZeroDivisionError:
x = 0
i += 1
print(time.time())
# Version 2: use if-check.
v = 0
i = 0
while i < 10000000:
if v != 0:
x = 10 / v
else:
x = 0
i += 1
print(time.time())
Output
1346178493.989
1346178499.7 (Version 1 = 5.711 s)
1346178501.788 (Version 2 = 2.088 s)