Python Exception Handling

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 21

Python Exception Handling: try, catch, finally & raise [Example]

What is an Exception Handling in Python?


An exception is an error which happens at the time of execution of a program. However, while
running a program, Python generates an exception that should be handled to avoid your program to
crash. In Python language, exceptions trigger automatically on errors, or they can be triggered and
intercepted by your code.
The exception indicates that, although the event can occur, this type of event happens infrequently.
When the method is not able to handle the exception, it is thrown to its caller function. Eventually,
when an exception is thrown out of the main function, the program is terminated abruptly.

In this Python exceptional handling tutorial, you will learn :


 What is an Exception in Python?
 Common Examples of Exception
 Why should you use Exceptions?
 Rules of Exceptions
 Python Exception Handling Mechanism
 Python Try Statement
 Python Catch Statement
 Raise Statement in Python
 Important Python Errors
 Other Important Python Exceptions
 Error vs. Exceptions

Common Examples of Exception:


 Division by Zero
 Accessing a file which does not exist.
 Addition of two incompatible types
 Trying to access a nonexistent index of a sequence
 Removing the table from the disconnected database server.
 ATM withdrawal of more than the available amount

Why should you use Exceptions?


Here are the reasons for using exceptions in Python:
 Exception handling allows you to separate error-handling code from normal code.
 An exception is a Python object which represents an error.
 As with code comments, exceptions helps you to remind yourself of what the program
expects.
 It clarifies the code and enhances readability.
 Allows you to stimulate consequences as the error-handling takes place at one place and in
one manner.
 An exception is a convenient method for handling error messages.
 In Python, you can raise an exception in the program by using the raise exception method.
 Raising an exception helps you to break the current code execution and returns the
exception back to expection until it is handled.
 Processing exceptions for components which can’t handle them directly.

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.

Python Exception Handling Mechanism


Exception handling is managed by the following 5 keywords:
1. try
2. catch
3. finally
4. throw

Python Try Statement


A try statement includes keyword try, followed by a colon (:) and a suite of code in which
exceptions may occur. It has one or more clauses.
During the execution of the try statement, if no exceptions occurred then, the interpreter
ignores the exception handlers for that specific try statement.
In case, if any exception occurs in a try suite, the try suite expires and program control
transfers to the matching except handler following the try suite.

Syntax:
try:
statement(s)

The catch Statement


Catch blocks take one argument at a time, which is the type of exception that it is likely to
catch. These arguments may range from a specific type of exception which can be varied to
a catch-all category of exceptions.

Rules for catch block:


 You can define a catch block by using the keyword catch
 Catch Exception parameter is always enclosed in parentheses
 It always represents the type of exception that catch block handles.
 An exception handling code is written between two {} curly braces.
 You can place multiple catch block within a single try block.
 You can use a catch block only after the try block.
 All the catch block should be ordered from subclass to superclass exception.

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.

Raise Statement in Python


The raise statement specifies an argument which initializes the exception object. Here, a
comma follows the exception name, and argument or tuple of the argument that follows
the comma.
Syntax:
raise [Exception [, args [, traceback]]]
In this syntax, the argument is optional, and at the time of execution, the exception
argument value is always none.

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.

Important Python Errors

Error Type Description


ArithmeticError act as a base class for all arithmetic exceptions. It is raised for errors in arithmetic
ArithmeticError
operations.
ImportError is raised when you are trying to import a module which does not present. This kind of
ImportError exception occurs if you have made typing mistake in the module name or the module which is not
present in the standard path.
IndexError An IndexErroris raised when you try to refer a sequence which is out of range.
KeyError When a specific key is not found in a dictionary, a KeyError exception is raised.
A NameError is raised when a name is referred to in code which never exists in the local or global
NameError
namespace.
Value error is raised when a function or built-in operation receives an argument which may be of
ValueError
correct type but does not have suitable value.
This kind of error raises when one of the built-in functions (input() or raw_input()) reaches an EOF
EOFerror
condition without reading any data.
ZeroDivisonError This type of error raised when division or module by zero takes place for all numeric types.
IOError- This kind of error raised when an input/output operation fails.
syntaxError SyntaxErrors raised when there is an error in Python syntax.
IndentationError This error raised when indentation is not properly defined

Other Important Python Exceptions


Exception Description
ArithmeticException Arithmetic error, such as divide-by-zero.
ArraylndexOutOfBoundsException Array index is out-of-bounds.
ArrayStoreException Assignment helps you to the array element of an incompatible type.
ClassCastException Invalid cast
MlegalMonitorStateException Illegal monitor operation, like waiting on an unlocked thread.
MlegalStateException Environment or application is in wrong state.
ClassNotFoundException Class not found.
CloneNotSupportedException Attempt to clone an object which does not implement the Cloneable interface.
Illegal AccessException Access to a class is denied.
InstantiationException Occurs when you attempt to create an object of an interface or abstract class.
CloneNotSupportedException Attempt to clone an object which does not implement the interface.

Error vs. Exceptions


Error Exceptions
All errors in Python are the unchecked type. Exceptions include both checked and unchecked type.
Exceptions can be recover by handling them with the help
Errors occur at run time which unknown to the compiler.
of try-catch blocks.
Errors are mostly caused by the environment in which an
The application itself causes exceptions.
application is running.
Examples:
Examples:
Checked Exceptions, SQL exception,
OutofMemoryError
NullPointerException,etc.
Summary
 An exception is an error which happened during the execution of a program.
 The exception indicates that, although the event can occur, this type of event happens
infrequently.
 Common Examples of Exception are 1) Division by Zero, 2) Accessing a file which is not
existent, 3) Addition of two incompatible types.
 An exception is a Python object which represents an error.
 A try statement includes keyword try, followed by a colon (:) and a suite of code in which
exceptions may occur. It has one or more clauses.
 Catch blocks take one argument at a time, which is the type of exception that it is likely to
catch.
 The raise statement specifies an argument which initializes the exception object.
 Finally, block always executes irrespective of an exception being thrown or not.

Mastering Exception Handling in Python: Best Practices


and Tips
Python’s ability to handle exceptions gracefully is one of the language’s
strengths. It allows developers to write robust and reliable code handling
unexpected situations.
However, proper exception handling is often overlooked or not fully
understood. This post will explore the ins and outs of exception handling in
Python, from the basics of try-except blocks to the best practices for raising and
handling custom exceptions.

Introduction: Importance of Exception Handling in Python


Exceptions are events that disrupt the normal flow of instructions. They allow
for detecting and handling errors and unexpected situations. As a Python
developer, it’s essential to have a solid understanding of handling exceptions
effectively.
When an exception is encountered, Python will stop executing the current code
and jump to the nearest exception handler. This allows the program to
continue running and prevents it from crashing. However, if an exception is not
handled properly, it can lead to bugs, data loss, and even security
vulnerabilities.
Proper exception handling is often overlooked or not fully understood, which is
why we will explore the ins and outs of exception handling in Python in this
post. We will cover the basics of try-except blocks, provide tips and tricks for
debugging and logging exceptions, and discuss best practices for raising and
handling custom exceptions.
Here is a simple example of using a try-except block in Python:

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.

Understanding Exceptions in Python


When an exception is encountered, Python will stop executing the current code
and jump to the nearest exception handler. This allows the program to
continue running and prevents it from crashing.
Python has two types of exceptions: built-in exceptions and user-defined
exceptions. Built-in exceptions are already defined in Python, such
as ZeroDivisionError, FileNotFoundError, TypeError, etc. These exceptions are
raised automatically by Python when a specific condition occurs.
On the other hand, the developer creates and raises user-defined exceptions.
Here is an example of a user-defined exception:

class MyException(Exception):
pass

raise MyException("An error occurred")

In this example, we define a new exception class, MyException, inherited from


the built-in Exception class. We then raise an instance of this class, passing in an
error message.
It’s important to note that, in Python, all exceptions are derived from the built-
in BaseException class. This means that you can catch any exception by catching
the BaseException class.
However, it’s generally recommended to catch specific exception types as it
allows for more fine-grained control over how the exceptions are handled.

Handling Exceptions in Python


The most common way to handle exceptions is by using try-except blocks. A try-
except block allows you to try some code and except certain exceptions that
may occur.
Here’s an example of a try-except block:

try:
x=1/0
except ZeroDivisionError:
print("You can't divide by zero!")

In this example, we try to divide 1 by 0, which will raise a ZeroDivisionError. The


except block catches this specific exception and prints a message.
You can also use the finally block, which will be executed no matter what:

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"

It is important to note that handling an exception is not always necessary;


sometimes, it’s better to let it propagate up the call stack.

Best Practices for Exception Handling


Let’s discuss some best practices for exception handling in Python. Following
these guidelines ensures that your code is clean, maintainable, and effective at
handling exceptions.
First and foremost, it’s essential to be specific when catching exceptions.
Instead of catching the broad Exception class, try to catch specific exception
types. This allows you to handle each exception in a particular way and prevent
unexpected behavior.

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

Additionally, it’s essential to be mindful of performance when handling


exceptions. Exceptions are slower than regular code, so it’s best to avoid using
them in performance-critical sections of your code.
Another best practice is to use context managers when working with resources
that require cleanup, such as file handles. The with statement ensures that the
resources are correctly closed, even if an exception is raised:

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.

Debugging and Logging


When it comes to debugging and logging, there are several tools and
techniques available in Python that can help you identify and fix exceptions in
your code.
One of the most basic and widely used debugging techniques is
the print() statement. By inserting print() statements in strategic places in your
code, you can see the values of variables and trace the execution flow. This can
help you identify where an exception is occurring and what is causing it. For
example:

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

def divide(x, y):


pdb.set_trace()
return x / y
try:
divide(1, 0)
except ZeroDivisionError as e:
print(e)

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.

Raising Custom Exceptions


Sometimes, the built-in exceptions provided by Python may not be specific
enough to handle the errors that can occur in your code. Creating custom
exceptions tailored to your particular use case can be useful.
To create a custom exception, you must create a new class that inherits from
the Exception class. For example:

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:

def divide(x, y):


if y == 0:
raise DivideByZeroException("Cannot divide by zero")
return x / y

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.

How to Catch, Raise, and Print a Python Exception


https://www.coursera.org/tutorials/python-exception#commonly-raised-built-in-
exceptions

Materials Required: Latest version of Python (Python 3), an integrated


development environment (IDE) of your choice (or terminal), stable internet
connection

Prerequisites/helpful expertise: Basic knowledge of Python and programming


concepts
Exceptions are extremely useful tools for Python programmers. They enable you
to handle errors, write more readable code, and simulate implementation
consequences. By the end of this tutorial, you will be able to use Python
exceptions to code more efficiently.
Glossary
Term Definition

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.

What is an exception in Python?


Exceptions are also known as logical errors. They occur during a program’s
execution. Rather than allowing the program to crash when an error is detected,
Python generates an exception you can handle. It’s comparable to the way an
iPhone displays a temperature warning when your phone gets too hot. Instead of
allowing the phone to overheat, it stops itself from functioning and prompts you
to resolve the issue by cooling it down. Similarly, Python exceptions halt the
program and provide you with an opportunity to resolve the error instead of
crashing.
There are two types of Python exceptions:
1. User-defined exceptions: User-defined exceptions are custom exceptions
created by programmers. They enable you to enforce restrictions or
consequences on certain functions, values, or variables.
2. Built-in exceptions: There are many different types of exceptions pre-defined by
Python. These are called built-in exceptions. You can find a reference table
defining each type of built-in exception at the bottom of this page or our Python
Exception Handling Cheat Sheet.
Exceptions vs. syntax errors
Exceptions Syntax errors

Change the normal flow of a Stop the execution of a program entirely


program

Occur during execution, and are not Generated during parsing, when source code
always inoperable is translated into byte code

Can be handled at runtime Cannot be handled

You can learn more about Python syntax errors in the previous tutorial in this
series, How to Identify and Resolve Python Syntax Errors.

Exception error messages


When an exception is raised in your code, Python prints a traceback. Tracebacks
provide you with information regarding why an error may have occurred. Here is
an
example:

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:

 The keyword try


 A colon
 The code block that may cause an error
Next, write the code you want to handle the exceptions in the except clause. This
allows you to tell the program which operations to perform once the exception in
the try block has been caught. Here’s an
example:

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.

How to catch a specific exception


The method above demonstrates how to catch all exceptions in Python.
However, many different types of errors can arise from the code you put inside
the try block. If you don’t specify which exceptions a particular except clause
should catch, it will handle each one the same way. You can address this issue in
a few ways. For example, you can anticipate the errors that may occur and add
corresponding except blocks for each one.

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")

You can also specify multiple exceptions at once:

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

Learn more: How to Use a Python If-Else Statement

Why do we use try and except in Python?


Python attempts to execute the statements within the try clause first. If an error
occurs, it skips the rest of the clause and prompts the program to follow your
except clause instructions. Instead of manually instructing the program each time
it encounters a given error, it can handle it automatically. Additionally, handling
exceptions this way enables you to replace the interpreter’s error message with a
much more user friendly one.
How to raise an exception in Python
The raise statement allows you to force an error to occur. You can define both the
type of error and the text that prints to the user. Note that the argument to raise
must either be an exception instance or a subclass deriving from exception.

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

if not type(x) is str:


raise TypeError("Sorry, only strings are allowed")

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

if #YOUR CODE HERE:

How to print an exception in Python


In an exception block, define the exception and use the print() function. Here’s an
example:

1
2
3
4
5
6
7
8
a = 5
b = 0

try:
quotient = a / b
print(quotient)
except Exception as X:
print(X)

Why isn’t Python printing my exception? If you’re having trouble getting


your exception error message to print, double check the code inside your
try-except block. It’s possible that the exception is not being raised,
causing the code to run without hitting the exception handler.
Commonly raised built-in exceptions
The chart below outlines a few of the most commonly encountered exceptions in
Python. You can view a more comprehensive list of built-in Python exceptions in
our Python Exception Handling Cheat Sheet.
Exception Explanation Hierarchy

AttributeError When an attribute reference or assignment Inherits from Exception.


fails, this Python exception is raised.

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.

ImportError Raised when an import statement struggles Inherits from Exception.


to load a module. Can also be raised when a
“from list” in from...import includes a name
it cannot find.

ModuleNotFoundErro Also raised by import. Occurs when a Inherits


r module cannot be located or when None is from Exception and is a
found in sys.modules. subclass of ImportError.

ZeroDivisionError Python raises this type of error when the Inherits


second argument of a modulo operation or a from Exception and is a
division is 0. subclass
of ArithmeticError.

IndexError This exception occurs if a sequence Inherits from Exception.


subscript is out of range.

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.

NameError When a global or local name cannot be Inherits from Exception.


found, this type of error is raised. The
conditions for this exception only apply to
unqualified names.
Exception Explanation Hierarchy

ConnectionError Base class for issues related to connection. Inherits from Exception,
belongs to the subclass of
OS exceptions.

TypeError If an operation or function is applied to an Inherits from Exception.


object of improper type, Python raises this
exception.

ValueError Raised when an operation or function Inherits from Exception.


receives the right type of argument but the
wrong value and it cannot be matched by a
more specific exception.

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.

You might also like