Exception Handling
Python Exception Handling handles errors that occur during the execution
of a program. Exception handling allows to respond to the error, instead of
crashing the running program. It enables you to catch and manage errors,
making your code more robust and user-friendly.
Program without try-except
numerator = 10
denominator = 0
result = numerator/denominator
print(result)
Output:
Traceback (most recent call last):
File "C:/Users/admin/p1.py", line 3, in <module>
result = numerator/denominator
ZeroDivisionError: division by zero
Program with try-except
try:
numerator = 10
denominator = 0
result = numerator/denominator
print(result)
except:
print("Error: Denominator cannot be 0.")
output
Error: Denominator cannot be 0
Example 3: Trying to divide a number by zero will cause an exception.
# Example of an exception
n = 10
try:
res = n / 0 # This will raise a ZeroDivisionError
except ZeroDivisionError:
print("Can't be divided by zero!")
Output
Can't be divided by zero!
Explanation: A syntax error is a coding mistake that prevents the code
from running. In contrast, an exception like ZeroDivisionError can be
managed during the program’s execution using exception handling.
Exception handling in Python is done using the try, except, else and finally
blocks.
Syntax
try:
# Code that might raise an exception
except SomeException:
# Code to handle the exception
else:
# Code to run if no exception occurs
finally:
# Code to run regardless of whether an exception occurs
Where try, except, else and finally Blocks
try Block: try block will test a block of code for errors. If an exception
occurs, execution will immediately jump to the except block.
except Block: except block enables us to handle the error or exception.
If the code inside the try block throws an error, Python jumps to the
except block and executes it
else Block: else block is optional and if included, must follow all except
blocks. The else block runs only if no exceptions are raised in the try
block.
finally Block: finally block always runs, regardless of whether an
exception occurred or not. It is typically used for cleanup operations
(closing files, releasing resources).
The try block lets you test a block of code for errors.
The except block lets you handle the error.
The else block lets you execute code when there is no error.
The finally block lets you execute code, regardless of the result of
the try- and except blocks.
Example:
try:
n = 0
res = 100 / n
except ZeroDivisionError:
print("You can't divide by zero!")
except ValueError:
print("Enter a valid number!")
else:
print("Result is", res)
finally:
print("Execution complete.")
Output
You can't divide by zero!
Execution complete.
Explanation:
try block asks for user input and tries to divide 100 by the input
number.
except blocks handle ZeroDivisionError and ValueError.
else block runs if no exception occurs, displaying the result.
finally block runs regardless of the outcome, indicating the completion
of execution.
Common Exceptions in Python
Python has many built-in exceptions, each representing a specific error
condition. Some common ones include:
Built-in Python Exceptions:
list of default Python exceptions with descriptions:
1. AssertionError: raised when the assert statement fails.
2. EOFError: raised when the input() function meets the end-of-file condition.
3. AttributeError: raised when the attribute assignment or reference fails.
4. TabError: raised when the indentations consist of inconsistent tabs or
spaces.
5. ImportError: raised when importing the module fails.
6. IndexError: occurs when the index of a sequence is out of range
7. KeyboardInterrupt: raised when the user inputs interrupt keys (Ctrl + C or
Delete).
8. RuntimeError: occurs when an error does not fall into any category.
9. NameError: raised when a variable is not found in the local or global scope.
10. MemoryError: raised when programs run out of memory.
11. ValueError: occurs when the operation or function receives an
argument with the right type but the wrong value.
12. ZeroDivisionError: raised when you divide a value or variable with 0.
13. SyntaxError: raised by the parser when the Python syntax is wrong.
14. IndentationError: occurs when there is a wrong indentation.
15. SystemError: raised when the interpreter detects an internal error.
Python Catching Exceptions
When working with exceptions in Python, we can handle errors more
efficiently by specifying the types of exceptions we expect. This can make
code both safer and easier to debug.
Catching Specific Exceptions
Catching specific exceptions makes code to respond to different exception
types differently.
Example:
try:
x = int("str") # This will cause ValueError
#inverse
inv = 1 / x
except ValueError:
print("Not Valid!")
except ZeroDivisionError:
print("Zero has no inverse!")
Output
Not Valid!
Explanation:
The ValueError is caught because the string “str” cannot be converted
to an integer.
If x were 0 and conversion successful, the ZeroDivisionError would be
caught when attempting to calculate its inverse.
Catching Multiple Exceptions
We can catch multiple exceptions in a single block if we need to handle
them in the same way or we can separate them if different types of
exceptions require different handling.
Example:
a = ["10", "twenty", 30] # Mixed list of integers and strings
try:
total = int(a[0]) + int(a[1]) # 'twenty' cannot be converted to
int
except (ValueError, TypeError) as e:
print("Error", e)
except IndexError:
print("Index out of range.")
Output
Error invalid literal for int() with base 10: 'twenty'
Explanation:
The ValueError is caught when trying to convert “twenty” to an integer.
TypeError might occur if the operation was incorrectly applied to non-
integer types, but it’s not triggered in this specific setup.
IndexError would be caught if an index outside the range of the list was
accessed, but in this scenario, it’s under control.
Catch-All Handlers and Their Risks
Here’s a simple calculation that may fail due to various reasons.
Example:
try:
# Simulate risky calculation: incorrect type operation
res = "100" / 20
except ArithmeticError:
print("Arithmetic problem.")
except:
print("Something went wrong!")
Output
Something went wrong!
Explanation:
An ArithmeticError (more specific like ZeroDivisionError) might be
caught if this were a number-to-number division error. However,
TypeError is actually triggered here due to attempting to divide a string
by a number.
catch-all except: is used to catch the TypeError, demonstrating the
risk that the programmer might not realize the actual cause of the error
(type mismatch) without more detailed error logging.
Raise an Exception
We raise an exception in Python using the raise keyword followed by an
instance of the exception class that we want to trigger. We can choose
from built-in exceptions or define our own custom exceptions by inheriting
from Python’s built-in Exception class.
Basic Syntax:
raise ExceptionType(“Error message”)
Example:
def set(age):
if age < 0:
raise ValueError("Age cannot be negative.")
print(f"Age set to {age}")
try:
set(-5)
except ValueError as e:
print(e)
Output
Age cannot be negative.
Explanation:
The function set checks if the age is negative. If so, it raises a
ValueError with a message explaining the issue.
This ensures that the age attribute cannot be set to an invalid state,
thus maintaining the integrity of the data.
Advantages of Exception Handling:
Improved program reliability: By handling exceptions properly, you
can prevent your program from crashing or producing incorrect results
due to unexpected errors or input.
Simplified error handling: Exception handling allows you to separate
error handling code from the main program logic, making it easier to
read and maintain your code.
Cleaner code: With exception handling, you can avoid using complex
conditional statements to check for errors, leading to cleaner and more
readable code.
Easier debugging: When an exception is raised, the Python
interpreter prints a traceback that shows the exact location where the
exception occurred, making it easier to debug your code.
Exception Handling
When an error occurs, or exception as we call it, Python will normally stop
and generate an error message.
These exceptions can be handled using the try statement:
ExampleGet your own Python Server
The try block will generate an exception, because x is not defined:
try:
print(x)
except:
print("An exception occurred")
Example
This statement will raise an error, because x is not defined:
print(x)
Else
You can use the else keyword to define a block of code to be executed if no
errors were raised:
Example
In this example, the try block does not generate any error:
try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")
Finally
The finally block, if specified, will be executed regardless if the try block
raises an error or not.
Example
try:
print(x)
except:
print("Something went wrong")
finally:
print("The 'try except' is finished")
Raise an exception
As a Python developer you can choose to throw an exception if a condition
occurs.
To throw (or raise) an exception, use the raise keyword.
Example
Raise an error and stop the program if x is lower than 0:
x = -1
if x < 0:
raise Exception("Sorry, no numbers below zero")
The raise keyword is used to raise an exception.
You can define what kind of error to raise, and the text to print to the user.
Example
Raise a TypeError if x is not an integer:
x = "hello"
if not type(x) is int:
raise TypeError("Only integers are allowed")
An error is an issue in a program that prevents the program from completing
its task. In comparison, an exception is a condition that interrupts the normal
flow of the program. Both errors and exceptions are a type of runtime error,
which means they occur during the execution of a program.
In simple words, the error is a critical issue that a normal application should
not catch, while an exception is a condition that a program should catch.
Definition:
Exception handling allows to respond to the error, instead of crashing the running program. It
enables you to catch and manage errors, making your code more robust and user-friendly.
Example: Trying to divide a number by zero will cause an exception