Python Exception Handling
Python Exception Handling
Rules of Exceptions
Here are some essential rules of Python exception handling:
Exceptions must be class objects
For class exceptions, you can use try statement with an except clause which
mentions a particular class.
Even if a statement or expression is syntactically correct, it may display an error
when an attempt is made to execute it.
Errors found during execution are called exceptions, and they are not
unconditionally fatal.
Syntax:
try:
statement(s)
Example:
try
}
catch (ArrayIndexOutOfBoundsException e) {
System.err.printin("Caught first " + e.getMessage()); } catch (IOException e) {
System.err.printin("Caught second " + e.getMessage());
}
Finally Statement in Python
Finally block always executes irrespective of an exception being thrown or not. The final keyword
allows you to create a block of code that follows a try-catch block.
Finally, clause is optional. It is intended to define clean-up actions which should be that executed in
all conditions.
try:
raise KeyboardInterrupt
finally:
print 'welcome, world!'
Output
Welcome, world!
KeyboardInterrupt
Finally, clause is executed before try statement.
Example:
A Python exception can be any value like a string, class, number, or an object. Most of these
exceptions which are raised by Python core are classes with an argument which is an
instance of the class.
try:
# some code here
except ExceptionType as e:
# handle the exception
The code within the try block is executed in the above code snippet. If an
exception of the specified ExceptionType is raised, the code within the except
block is executed. This allows you to handle the exception and prevent the
program from crashing.
This post will dive into how exception handling works in Python, explain the
different types of exceptions and errors, and provide best practices for writing
clean and effective exception-handling code. We will also explore the various
tools and techniques you can use to debug and log exceptions.
By the end of this post, you will have a solid understanding of handling
exceptions in Python. You can write robust and reliable code that can handle
unexpected situations.
class MyException(Exception):
pass
try:
x=1/0
except ZeroDivisionError:
print("You can't divide by zero!")
try:
x=1/0
except ZeroDivisionError:
print("You can't divide by zero!")
finally:
print("This code will always be executed")
You can also use the else block, which will be executed if the try block doesn't
raise an exception:
try:
x=1/1
except ZeroDivisionError:
print("You can't divide by zero!")
else:
print("No exception was raised")
Another way to handle exceptions is by using the raise statement. This allows
you to raise an exception manually. For example:
if x == 0:
raise ZeroDivisionError("x cannot be zero")
You can also use the assert statement to raise an exception if a certain
condition is not met. This is useful for debugging and for adding validation to
your code. For example:
assert x != 0, "x cannot be zero"
try:
x=1/0
except ZeroDivisionError:
print("You can't divide by zero!")
except TypeError:
print("You can't divide by a string")
It’s also a good practice to avoid empty except blocks. An empty except block
doesn’t provide any information about what went wrong and makes it difficult
to debug. If you don’t know how to handle an exception, it’s better to let it
propagate up the call stack.
try:
x=1/0
except ZeroDivisionError:
pass # This block doesn't provide any information about the error
with open("file.txt") as f:
# Do something with the file
# File is automatically closed here, even if an exception was raised
Finally, it’s important to log and debug exceptions. Python provides a built-in
logging module that you can use to log exceptions. This allows you to track and
fix bugs quickly.
import logging
try:
x=1/0
except ZeroDivisionError as e:
logging.error(e)
Following these best practices, you can write clean and effective exception-
handling code in Python. Remember that exceptions are a powerful tool for
handling errors, but they should be used judiciously and with care.
try:
x=1/0
except ZeroDivisionError as e:
print(e)
print("x:", x)
Another useful debugging tool is the pdb module, a built-in Python library for
interactive debugging. This allows you to step through your code line by line
and inspect variables and the call stack. To use the pdb module, you can
insert import pdb; pdb.set_trace() at the point in your code where you want to
start debugging. For example:
import pdb
In addition to debugging, it’s also important to use logging to track and fix
exceptions. Python provides a built-in logging module that you can use to log
exceptions and other events in your code. By default, the logging module logs
messages to the console, but you can also configure it to log to a file or send
messages to a remote server. For example:
import logging
logging.basicConfig(level=logging.ERROR)
try:
x=1/0
except ZeroDivisionError as e:
logging.error(e)
Another logging library that is widely used is logging. It's a library that provides
a more flexible and powerful logging API than the built-in logging module. The
library allows you to add custom loggers, formatters, and handlers.
class DivideByZeroException(Exception):
pass
You can also define custom exception classes that inherit from specific built-in
exceptions to indicate that the custom exception is a more specific type of
built-in exception. For example:
class InvalidInputException(ValueError):
pass
Once you have defined your custom exception class, you can raise it using
the raise statement. For example:
try:
divide(1, 0)
except DivideByZeroException as e:
print(e)
It’s also possible to define custom exceptions with additional attributes and
methods that store extra information. For example:
class MyCustomException(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
You can pass in any arguments required by the custom exception class’s
constructor when raising a custom exception. This allows you to attach
additional information to the exception, such as the invalid input that caused
the exception.
Creating and raising custom exceptions can help make your code more
readable and maintainable by providing more specific error messages and
making it easier to identify and handle particular errors. It’s important to
remember that custom exceptions should be used sparingly and only when the
built-in exceptions do not provide enough information or functionality to
handle the errors that can occur in your code.
Conclusion
In conclusion, exception handling is vital for writing reliable and maintainable
code in Python. We have covered the basics of exceptions, how they work in
Python, the different ways to handle exceptions using try-except blocks, and
the raise statement.
We also discussed best practices for writing clean and effective exception-
handling code and techniques for debugging and logging to help identify and fix
exceptions in your code. We also discussed how to create and raise custom
exceptions in Python.
By understanding and following best practices for exception handling, you can
write code that is more robust and less prone to errors.
I hope this post has provided valuable insights and tips for improving your
exception-handling skills in Python.
Print print() is a function that converts a specified object into text and sends it to the
screen or other standard output device.
Raise raise() is a function that interrupts the normal execution process of a program. It
signals the presence of special circumstances such as exceptions or errors.
Throw The term “throw” is used synonymously with “raise.” However, “throw” is not a
Python keyword.
Traceback When an error occurs, you can trace it backto the source using this Python module.
A traceback reports the function calls made at a given point in your code.
Tracebacks are read from the bottom upward.
Syntax Syntax is the set of rules that defines the structure of a language. A syntax error
Error indicates you have entered a character or string that the program’s interpreter
cannot understand.
try "Try" is a Python keyword. It enables you to test a code block for errors.
except "Except" is a Python keyword that is used to handle exceptions arising in the
previous try clause.
Occur during execution, and are not Generated during parsing, when source code
always inoperable is translated into byte code
You can learn more about Python syntax errors in the previous tutorial in this
series, How to Identify and Resolve Python Syntax Errors.
The last line in the code block shown above indicates the type of exception that
has occurred. You can learn more about tracebacks with the next tutorial in this
series, How to Retrieve, Print, Read, and Log a Python Traceback.
How to use try and except in Python to catch
exceptions
To catch a Python exception, use a try statement. A try statement includes:
In the above example, the code beneath the try keyword throws a TypeError,
since you cannot add a string type to an integer type. This prompts the
interpreter to run the except block instead.
Try it yourself
How would you revise this code with try and except to avoid generating a
traceback?
1
2
3
a = 5
b = 0
quotient = a / b
What if the try block executes without error? If you want the program to
take action even when the try block succeeds, use an else block after the
except block.
1
2
3
4
5
6
7
8
9
10
11
12
a = 5
b = "zero"
try:
quotient = a / b
print(quotient)
except ZeroDivisionError:
print("You cannot divide by zero")
except TypeError:
print("You must convert strings to floats or integers before dividing")
except NameError:
print("A variable you're trying to use does not exist")
1
2
3
4
5
6
7
8
a = 5
b = "zero"
try:
quotient = a / b
print(quotient)
except (ZeroDivisionError, TypeError):
print("This division is impossible")
Suppose you want to implement a few special cases but handle all other
exceptions the same. In that case, you can create an except block to handle all
other exceptions:
1
2
3
4
5
6
7
8
9
10
a = 5
b = 0
try:
quotient = a / c
print(quotient)
except (ZeroDivisionError, TypeError):
print("You cannot divide by zero and variables must be floats or integers")
except:
print("Other error")
Try it yourself
Add an except statement to this code that prints "You can only concatenate
strings to strings" if there's a TypeError and "Something else went wrong" for any
other type of error.
1
2
greeting = word1+word2
print(greeting)
Solution
Expand to view solution
Example: Suppose you want to raise an error and stop the program if a variable is
anything but a string. In that case, you could write the following exception:
1
2
3
4
x = -5
In the code block above, TypeError is the specified error. It has been set to occur
anytime the variable x is not a string. The text inside the parentheses represents
your chosen text to print to the user.
Try it yourself
How would you raise an exception that prints "Sorry, please enter a number
greater than or equal to 0" if x is a negative number?
1
2
3
x = -5
1
2
3
4
5
6
7
8
a = 5
b = 0
try:
quotient = a / b
print(quotient)
except Exception as X:
print(X)
EOFError EOF stands for end-of-file. This exception is Inherits from Exception.
raised when an input() function reaches an
EOF condition without reading any data.
KeyError Raised when a mapping key or, dictionary Inherits from Exception.
key, is not found in the existing set of keys.
MemoryError Raised when there is not enough memory for Inherits from Exception.
the current operation. This exception can be
addressed by deleting other objects.
ConnectionError Base class for issues related to connection. Inherits from Exception,
belongs to the subclass of
OS exceptions.
Key takeaways
Exceptions occur during a program’s execution.
There are built-in exceptions and user-defined exceptions.
Base classes are not to be inherited by user-defined classes.
You can use try and except in Python to catch exceptions.