Errors and exceptions can lead to program failure or unexpected behavior, and Python comes with a robust set of tools to improve the stability of the code.
Errors and exceptions can lead to unexpected behavior or even stop a program from executing. Python provides various functions and mechanisms to handle these issues and improve the robustness of the code. In this tutorial, we will learn about various error types and built-in functions with examples.
An error is a critical problem in code that typically cannot be recovered from at runtime, such as malformed syntax or wrong indentation.
An exception is a runtime event that disrupts normal program flow but can be caught and handled, allowing the program to continue.
While exceptions occur at runtime, some errors like SyntaxError and IndentationError are caught by the parser before the program even runs.
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.
Let’s learn more about errors and exceptions by looking at various examples. To easily run these, you can create a DataLab workbook for free that has Python pre-installed and contains all code samples.
Errors in Python
Here is an example of a syntax error where a return outside the function means nothing. We should not handle errors in a program. Instead, we must create a function that returns the string.
We have created the function but with the wrong indentation. We should not handle indentation errors at runtime. We can do it manually or use code formatting tools.
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
Input In [4],in<cell line:1>()---->1 test =1/0
ZeroDivisionError: division by zero
NameError exceptions are quite common where a variable is not found. We can also handle the exception either by replacing the variable or printing the warning.
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Input In [5],in<cell line:1>()---->1 y = test
NameError
Here is the list of default Python exceptions with descriptions:
AssertionError: raised when the assert statement fails.
EOFError: raised when the input() function meets the end-of-file condition.
AttributeError: raised when the attribute assignment or reference fails.
TabError: raised when the indentations consist of inconsistent tabs or spaces.
ImportError: raised when importing the module fails.
IndexError: occurs when the index of a sequence is out of range
KeyboardInterrupt: raised when the user inputs interrupt keys (Ctrl + C or Delete).
RuntimeError: occurs when an error does not fall into any category.
NameError: raised when a variable is not found in the local or global scope.
MemoryError: raised when programs run out of memory.
ValueError: occurs when the operation or function receives an argument with the right type but the wrong value.
ZeroDivisionError: raised when you divide a value or variable with zero.
SyntaxError: raised by the parser when the Python syntax is wrong.
IndentationError: occurs when there is a wrong indentation.
SystemError: raised when the interpreter detects an internal error.
You can find a complete list of errors and exceptions in Python by reading the documentation.
Learn about Python exceptions by taking our Object-Oriented Programming in Python course. It will teach you how to create classes and leverage inheritance and polymorphism to reuse and optimize code.
Exception Handling with try, except, else, and finally
After learning about errors and exceptions, we will learn to handle them by using try, except, else, and finally blocks.
So, what do we mean by handling them? In normal circumstances, these errors will stop the code execution and display the error message. To create stable systems, we need to anticipate these errors and come up with alternative solutions or warning messages.
In this section, we will learn what each block does and how we can use them to write robust code.
The try and except statement
The most simple way of handling exceptions in Python is by using the try and except block.
Run the code under the try statement.
When an exception is raised, execute the code under the except statement.
Instead of stopping at error or exception, our code will move on to alternative solutions.
Simple example
In the first example, we will try to print the undefined x variable. In normal circumstances, it should throw the error and stop the execution, but with the try and except block, we can change the flow behavior.
The program will run the code under the try statement.
As we know, that x is not defined, so it will run the except statement and print the warning.
try:print(x)except:print("An exception has occurred!")
In the second example, we will be using multiple except statements to handle multiple types of exceptions.
If a ZeroDivisionError exception is raised, the program will print "You cannot divide a value with zero."
The rest of the exceptions will print “Something else went wrong.”
It allows us to write flexible code that can handle multiple exceptions at a time without breaking.
Note: Avoid using a bare except: clause without specifying an exception type — it catches everything, including KeyboardInterrupt and SystemExit, which can make your program impossible to quit and hide unrelated bugs. Always catch the specific exception you expect, like except ZeroDivisionError:.
try:print(1/0)except ZeroDivisionError:print("You cannot divide a value with zero")except:print("Something else went wrong")Powered by
In the code below, we are reading the CSV file, and when it raises the FileNotFoundError exception, the code will print the error and an additional message about the data.csv file.
Yes, we can print default error messages without breaking the execution.
try:withopen('data.csv')asfile:
read_data =file.read()except FileNotFoundError as fnf_error:print(fnf_error)print("Explanation: We cannot load the 'data.csv' file")
We have learned about try and except, and now we will be learning about the else statement.
When the try statement does not raise an exception, code enters into the else block. It is the remedy or a fallback option when you expect a part of your script will produce an exception. It is generally used in a brief setup or verification section where you don't want certain errors to hide.
Note: In the try-except block, you can use the else after all the except statements.
Simple example
We are adding the else statement to the ZeroDivisionError example. As we can see, when there are no exceptions, the print function under the else statement is executed, displaying the result.
try:
result =1/3except ZeroDivisionError as err:print(err)else:print(f"Your answer is {result}")
Let’s learn more by creating a simple function and testing it for various scenarios.
The find_nth_value() function has x (list) and n (index number) as arguments. We have created a try, except, and else block to handle the IndexError exception.
x =[5,8,9,13]deffind_nth_value(x,n):try:
result = x[n]except IndexError as err:print(err)else:print("Your answer is ", result)
Errors and exceptions can lead to unexpected behavior or even stop a program from executing. Python provides various functions and mechanisms to handle these issues and improve the robustness of the code. In this tutorial, we will learn about various error types and built-in functions with examples.
While exceptions occur at runtime, some errors like
SyntaxErrorandIndentationErrorare caught by the parser before the program even runs.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.
Let’s learn more about errors and exceptions by looking at various examples. To easily run these, you can create a DataLab workbook for free that has Python pre-installed and contains all code samples.
Errors in Python
Here is an example of a syntax error where a return outside the function means nothing. We should not handle errors in a program. Instead, we must create a function that returns the string.
We have created the function but with the wrong indentation. We should not handle indentation errors at runtime. We can do it manually or use code formatting tools.
Exceptions in Python
We have encountered a
ZeroDivisionError(Exception). We can handle it at runtime by usingtryandexceptblocks.NameErrorexceptions are quite common where a variable is not found. We can also handle the exception either by replacing the variable or printing the warning.Built-in Python Exceptions
Here is the list of default Python exceptions with descriptions:
AssertionError: raised when the assert statement fails.EOFError: raised when theinput()function meets the end-of-file condition.AttributeError: raised when the attribute assignment or reference fails.TabError: raised when the indentations consist of inconsistent tabs or spaces.ImportError: raised when importing the module fails.IndexError: occurs when the index of a sequence is out of rangeKeyboardInterrupt: raised when the user inputs interrupt keys (Ctrl + C or Delete).RuntimeError: occurs when an error does not fall into any category.NameError: raised when a variable is not found in the local or global scope.MemoryError: raised when programs run out of memory.ValueError: occurs when the operation or function receives an argument with the right type but the wrong value.ZeroDivisionError: raised when you divide a value or variable with zero.SyntaxError: raised by the parser when the Python syntax is wrong.IndentationError: occurs when there is a wrong indentation.SystemError: raised when the interpreter detects an internal error.You can find a complete list of errors and exceptions in Python by reading the documentation.
Learn about Python exceptions by taking our Object-Oriented Programming in Python course. It will teach you how to create classes and leverage inheritance and polymorphism to reuse and optimize code.
Exception Handling with try, except, else, and finally
After learning about errors and exceptions, we will learn to handle them by using
try,except,else, andfinallyblocks.So, what do we mean by handling them? In normal circumstances, these errors will stop the code execution and display the error message. To create stable systems, we need to anticipate these errors and come up with alternative solutions or warning messages.
In this section, we will learn what each block does and how we can use them to write robust code.
The try and except statement
The most simple way of handling exceptions in Python is by using the
tryandexceptblock.Run the code under the
trystatement.When an exception is raised, execute the code under the
exceptstatement.Instead of stopping at error or exception, our code will move on to alternative solutions.
Simple example
In the first example, we will try to print the undefined
xvariable. In normal circumstances, it should throw the error and stop the execution, but with thetryandexceptblock, we can change the flow behavior.trystatement.xis not defined, so it will run the except statement and print the warning.Multiple except statement example
In the second example, we will be using multiple
exceptstatements to handle multiple types of exceptions.ZeroDivisionErrorexception is raised, the program will print "You cannot divide a value with zero."It allows us to write flexible code that can handle multiple exceptions at a time without breaking.
Note: Avoid using a bare
except:clause without specifying an exception type — it catches everything, includingKeyboardInterruptandSystemExit, which can make your program impossible to quit and hide unrelated bugs. Always catch the specific exception you expect, likeexcept ZeroDivisionError:.Loading the file example
Now, let’s look at a more practical example.
In the code below, we are reading the CSV file, and when it raises the
FileNotFoundErrorexception, the code will print the error and an additional message about thedata.csvfile.Yes, we can print default error messages without breaking the execution.
The try with else clause
We have learned about
tryandexcept, and now we will be learning about theelsestatement.When the
trystatement does not raise an exception, code enters into theelseblock. It is the remedy or a fallback option when you expect a part of your script will produce an exception. It is generally used in a brief setup or verification section where you don't want certain errors to hide.Note: In the try-except block, you can use the
elseafter all theexceptstatements.Simple example
We are adding the
elsestatement to theZeroDivisionErrorexample. As we can see, when there are no exceptions, the print function under theelsestatement is executed, displaying the result.IndexError with else example
Let’s learn more by creating a simple function and testing it for various scenarios.
The
find_nth_value()function hasx(list) andn(index number) as arguments. We have created atry,except, andelseblock to handle theIndexErrorexception.The list
xhas four values, and we will test them for the 6th and 2nd indexes.