🕷️ Crawler Inspector

URL Lookup

Direct Parameter Lookup

Raw Queries and Responses

1. Shard Calculation

Query:
Response:
Calculated Shard: 136 (from laksa181)

2. Crawled Status Check

Query:
Response:

3. Robots.txt Check

Query:
Response:

4. Spam/Ban Check

Query:
Response:

5. Seen Status Check

ℹ️ Skipped - page is already crawled

📄
INDEXABLE
CRAWLED
2 days ago
🤖
ROBOTS ALLOWED

Page Info Filters

FilterStatusConditionDetails
HTTP statusPASSdownload_http_code = 200HTTP 200
Age cutoffPASSdownload_stamp > now() - 6 MONTH0.1 months ago
History dropPASSisNull(history_drop_reason)No drop reason
Spam/banPASSfh_dont_index != 1 AND ml_spam_score = 0ml_spam_score=0
CanonicalPASSmeta_canonical IS NULL OR = '' OR = src_unparsedNot set

Page Details

PropertyValue
URLhttps://www.datacamp.com/tutorial/exception-handling-python
Last Crawled2026-04-15 05:52:01 (2 days ago)
First Indexed2022-04-14 03:29:45 (4 years ago)
HTTP Status Code200
Meta TitleException & Error Handling in Python | Tutorial by DataCamp | DataCamp
Meta DescriptionStruggling with error types? Learn how to catch and handle exceptions in Python with our step-by-step tutorial. Raise exceptions in Python and catch your errors today!
Meta Canonicalnull
Boilerpipe Text
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 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.  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.  return "DataCamp" Was this AI assistant helpful? Input In [ 1 ] return "DataCamp" ^ SyntaxError : 'return' outside function Was this AI assistant helpful? 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. def fun ( ) : return "DataCamp" Was this AI assistant helpful? Input In [ 2 ] return "DataCamp" ^ IndentationError : expected an indented block Was this AI assistant helpful? Exceptions in Python We have encountered a ZeroDivisionError (Exception). We can handle it at runtime by using try and except blocks. test = 1 / 0 Was this AI assistant helpful? - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ZeroDivisionError Traceback ( most recent call last ) Input In [ 4 ] , in < cell line : 1 > ( ) - - - - > 1 test = 1 / 0 ZeroDivisionError : division by zero Was this AI assistant helpful? 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.  y = test Was this AI assistant helpful? - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - NameError Traceback ( most recent call last ) Input In [ 5 ] , in < cell line : 1 > ( ) - - - - > 1 y = test NameError Was this AI assistant helpful? Built-in Python Exceptions 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!" ) Was this AI assistant helpful? An exception has occurred! Was this AI assistant helpful? Multiple except statement example 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.  try : print ( 1 / 0 ) except ZeroDivisionError : print ( "You cannot divide a value with zero" ) except : print ( "Something else went wrong" ) Was this AI assistant helpful? You cannot divide a value with zero Was this AI assistant helpful? 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 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 : with open ( 'data.csv' ) as file : read_data = file . read ( ) except FileNotFoundError as fnf_error : print ( fnf_error ) print ( "Explanation: We cannot load the 'data.csv' file" ) Was this AI assistant helpful? [ Errno 2 ] No such file or directory : 'data.csv' Explanation : We cannot load the 'data.csv' file Was this AI assistant helpful? The try with else clause 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 / 3 except ZeroDivisionError as err : print ( err ) else : print ( f"Your answer is { result } " ) Was this AI assistant helpful? Your answer is 0.3333333333333333 Was this AI assistant helpful? IndexError with else example 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 ] def find_nth_value ( x , n ) : try : result = x [ n ] except IndexError as err : print ( err ) else : print ( "Your answer is " , result ) Was this AI assistant helpful? The list x has four values, and we will test them for the 6th and 2nd indexes.  # Testing find_nth_value ( x , 6 ) find_nth_value ( x , 2 ) Was this AI assistant helpful? At n=6 , the IndexError exception was raised, and we got to see the error default message “list index out of range.”  At n=2 , no exception was raised, and the function printed the result which is under the else  statement.  list index out of range Your answer is 9 Was this AI assistant helpful? The finally keyword in Python The finally keyword in the try - except block is always executed, irrespective of whether there is an exception or not. In simple words, the finally  block of code is run after the try , except and else block is final. It is quite useful in cleaning up resources and closing the object, especially closing the files. The divide  function is created to handle ZeroDivisionError exceptions and display the result when there are no exceptions. No matter what the outcome is, it will always run finally  to print “Code by DataCamp” in green color. def divide ( x , y ) : try : result = x / y except ZeroDivisionError : print ( "Please change 'y' argument to non-zero value" ) except : print ( "Something went wrong" ) else : print ( f"Your answer is { result } " ) finally : print ( "\033[92m Code by DataCamp\033[00m" ) Was this AI assistant helpful? In the first test, we are dividing 1 by 0, which should raise the ZeroDivisionError exception and print the message. As we can see, we have an additional line after the error message.  divide ( 1 , 0 ) Was this AI assistant helpful? Please change 'y' argument to non - zero value Code by DataCamp Was this AI assistant helpful? When we add valid input, it displays the result by executing else and finally  blocking. divide ( 3 , 4 ) Was this AI assistant helpful? Your answer is 0.75 Code by DataCamp Was this AI assistant helpful? Instead of an integer, we have added a string as a second argument, which has raised an exception, that is different from ZeroDivisionError , with a different message.  divide ( 1 , 'g' ) Was this AI assistant helpful? Something went wrong Code by DataCamp Was this AI assistant helpful? In all three scenarios, there is one thing in common. The code is always running the print function under the finally  statement. If you are new to Python and want to code like a real programmer, try our Python Programming skill track. You will learn to write efficient code, Python functions, software engineering, unit testing, and object-oriented programming.  Nested Exception Handling in Python We need nested exception handling when we are preparing the program to handle multiple exceptions in a sequence. For example, we can add another try-except block under the else statement. So, if the first statement does not raise an exception, check the second statement with the other half of the code.  Modifying the divide function We have modified the divide function from the previous example and added a nested try-except block under the else  statement. So, if there is no AttributeError , it will run the else  and check the new code for the ZeroDivisionError exception. def divide ( x , y ) : try : value = 50 x . append ( value ) except AttributeError as atr_err : print ( atr_err ) else : try : result = [ i / y for i in x ] print ( result ) except ZeroDivisionError : print ( "Please change 'y' argument to non-zero value" ) finally : print ( "\033[92m Code by DataCamp\033[00m" ) Was this AI assistant helpful? In the first scenario, we provide the list of four values x and denominator 3. The script will add 50 to the list, divide the individual value in the list by 3, and display the result.  x = [ 40 , 65 , 70 , 87 ] divide ( x , 3 ) Was this AI assistant helpful? The function was successfully executed without raising any exceptions. [ 13.333333333333334 , 21.666666666666668 , 23.333333333333332 , 29.0 , 16.666666666666668 ] Code by DataCamp Was this AI assistant helpful? Instead of a list, we have provided an integer to the first argument, which has raised AttributeError . divide ( 4 , 3 ) Was this AI assistant helpful? 'int' object has no attribute 'append' Code by DataCamp Was this AI assistant helpful? In the last scenario, we have provided the list, but 0 is the second argument that has raised the ZeroDivisionError exception under the else  statement.  divide ( x , 0 ) Was this AI assistant helpful? Please change 'y' argument to non - zero value Code by DataCamp Was this AI assistant helpful? File editing example Let’s look at more practical examples of loading the file, writing a text, and closing the file.  The file_editor() function will: Check the FileNotFoundError exception for the open()  function. If the outer exception is not raised, it will check for the write()  function exception. No matter what, after opening the file, it will close the file by running the finally  statement.  If the outer try statement raises the exception, it will return the error message with an invalid file path.  def file_editor ( path , text ) : try : data = open ( path ) try : data . write ( text ) except : print ( "Unable to write the data. Please add an append: 'a' or write: 'w' parameter to the open() function." ) finally : data . close ( ) except : print ( f" { path } file is not found!!" ) Was this AI assistant helpful? In the first scenario, we provide the file path and the text. path = "data.txt" text = "DataLab: Share your data analysis in a cloud-based environment--no installation required." file_editor ( path , text ) The outer exception is raised.  data . txt file is not found!! Was this AI assistant helpful? To resolve the file not found exception, we must create a file data.txt using the Linux echo  command.  !echo "File by DataCamp" > "data.txt" Was this AI assistant helpful? After that, rerun the file_editor()  function. file_editor ( path , text ) Was this AI assistant helpful? The inner exception is raised, as the write()  function is not able to add the text. Unable to write the data . Please add an append : 'a' or write : 'w' parameter to the open ( ) function . Was this AI assistant helpful? To resolve this issue, we need to change the third line from data = open(path) to data = open(path, 'a') . It will allow us to append the new text to the file.  After rerunning the function, we successfully added the text to the file.  file_editor ( path , text ) Was this AI assistant helpful? Nested exception handling is not recommended as it makes exception handling more complex; developers use multiple try - except blocks to create simple sequential exception handling.  Note: you can also add a nested try - except block under the try or except  statement. It just depends on your requirements.  Raising Exceptions in Python As a Python developer, you can throw an exception if certain conditions are met. It allows you to interrupt the program based on your requirements.  To throw an exception, we have to use the raise  keyword followed by an exception name.  Raising value error example We can simply raise exceptions by adding a raise keyword in the if / else statement.  In the example, we raise the ValueError if the value exceeds 1,000. We have changed the value to 2,000, which has made the if  statement TRUE and raised ValueError with the custom message. The custom error message helps you figure out the problem quickly.  value = 2_000 if value > 1_000 : # raise the ValueError raise ValueError ( "Please add a value lower than 1,000" ) else : print ( "Congratulations! You are the winner!!" ) Was this AI assistant helpful? - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ValueError Traceback ( most recent call last ) - - - - > 4 raise ValueError ( "Please add a value lower than 1,000" ) 5 else : 6 print ( "Congratulations! You are the winner!!" ) ValueError : Please add a value lower than 1 , 000 Was this AI assistant helpful? Raising exception example We can also raise any random built-in Python exception if the condition is met. In our case, we have raised a generic Exception with the error message. if value > 1_000 : # raise the Exception raise Exception ( "Please add a value lower than 1,000" ) else : print ( "Congratulations! You are the winner!!" ) Was this AI assistant helpful? - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Exception Traceback ( most recent call last ) - - - - > 3 raise Exception ( "Please add a value lower than 1,000" ) 4 else : 5 print ( "Congratulations! You are the winner!!" ) Exception : Please add a value lower than 1 , 000 Was this AI assistant helpful? Handling raised exception example We can also create our custom exception and handle the exception by using the try - except block.  In the example, we have added a value error example under the try  statement.   So, how will it work? Instead of throwing the exception and terminating the program, it will display the error message we provided. value = 2_000 try : if value > 1_000 : # raise the ValueError raise ValueError ( "Please add a value lower than 1,000" ) else : print ( "Congratulations! You are the winner!!" ) # if false then raise the value error except ValueError as e : print ( e ) Was this AI assistant helpful? This type of exception handling helps us prepare for errors not covered by Python and are specific to your application requirement.  Please add a value lower than 1 , 000 Was this AI assistant helpful? What's New in Python 3.10 and 3.11 for Exception Handling? Some important new developments have been added to newer Python versions like 3.10 and 3.11 since the blog post was originally written: 1. Structural pattern matching in Python 3.10: Python 3.10 introduced structural pattern matching, which can be used to handle exceptions more elegantly by matching error types in a match statement. This is particularly useful when dealing with multiple exception types in a more readable way. Example: try : result = 1 / 0 except Exception as e : match e : case ZeroDivisionError ( ) : print ( "You cannot divide by zero." ) case NameError ( ) : print ( "Variable not defined." ) case _ : print ( "An unexpected error occurred." ) 2. Fine-grained error locations in tracebacks (Python 3.11): Tracebacks in Python 3.11 now show precise error locations, making it easier to debug exceptions. Before Python 3.11: value = ( 1 + 2 ) * ( 3 / 0 ) Traceback: ZeroDivisionError : division by zero Python 3.11: Tracebacks pinpoint the exact sub-expression causing the exception: 3. Exception groups and except* (Python 3.11): Python 3.11 introduced exception groups to handle multiple exceptions in a single block using except* . This is useful for managing asynchronous code or scenarios where multiple exceptions might be raised. Example: try : raise ExceptionGroup ( "Multiple errors" , [ ValueError ( "Bad value" ) , TypeError ( "Bad type" ) ] ) except * ValueError as ve : print ( f"Handling ValueError: { ve } " ) except * TypeError as te : print ( f"Handling TypeError: { te } " ) 4. add_note method for exceptions (Python 3.11): Exceptions now have an add_note() method, which allows developers to add custom notes to exceptions for better debugging. Example: try : raise ValueError ( "Invalid input" ) except ValueError as e : e . add_note ( "This happened while processing user input." ) e . add_note ( "Consider validating input before processing." ) raise Traceback: ValueError : Invalid input Notes : - This happened while processing user input . - Consider validating input before processing . 5. PEP 654: Better handling of nested exceptions: With exception groups, nested exceptions are now easier to debug and handle, especially in complex workflows like multiprocessing or asynchronous tasks. Conclusion Both  unit testing and exception handling are the core parts of Python programming that make your code production-ready and error-proof.  In this tutorial, we have learned about exceptions and errors in Python and how to handle them. Furthermore, we have learned about complex nested try-except blocks and created custom exception blocks based on requirements.   These tools and mechanisms are essential, but most of the work is done through simple try and except blocks. Where try looks for exceptions raised by the code and except  handles those exceptions.  If this is confusing and you don’t know where to start, complete our Introduction to Functions in Python course to understand scoping, lambda functions, and error handling. You can also enroll in the Python Programmer career track to gain career-building skills and become a professional Python developer. 
Markdown
[![Promo \| 50% Off](https://media.datacamp.com/cms/eng-8f1435.png) Last chance! **50% off** DataCamp Premium Sale ends in 3d12h06m16s Buy Now](https://www.datacamp.com/promo/flash-sale-apr-26) [Skip to main content](https://www.datacamp.com/tutorial/exception-handling-python#main) EN [English](https://www.datacamp.com/tutorial/exception-handling-python)[Español](https://www.datacamp.com/es/tutorial/exception-handling-python)[Português](https://www.datacamp.com/pt/tutorial/exception-handling-python)[DeutschBeta](https://www.datacamp.com/de/tutorial/exception-handling-python)[FrançaisBeta](https://www.datacamp.com/fr/tutorial/exception-handling-python)[ItalianoBeta](https://www.datacamp.com/it/tutorial/exception-handling-python)[TürkçeBeta](https://www.datacamp.com/tr/tutorial/exception-handling-python)[Bahasa IndonesiaBeta](https://www.datacamp.com/id/tutorial/exception-handling-python)[Tiếng ViệtBeta](https://www.datacamp.com/vi/tutorial/exception-handling-python)[NederlandsBeta](https://www.datacamp.com/nl/tutorial/exception-handling-python)[हिन्दीBeta](https://www.datacamp.com/hi/tutorial/exception-handling-python)[日本語Beta](https://www.datacamp.com/ja/tutorial/exception-handling-python)[한국어Beta](https://www.datacamp.com/ko/tutorial/exception-handling-python)[PolskiBeta](https://www.datacamp.com/pl/tutorial/exception-handling-python)[RomânăBeta](https://www.datacamp.com/ro/tutorial/exception-handling-python)[РусскийBeta](https://www.datacamp.com/ru/tutorial/exception-handling-python)[SvenskaBeta](https://www.datacamp.com/sv/tutorial/exception-handling-python)[ไทยBeta](https://www.datacamp.com/th/tutorial/exception-handling-python)[中文(简体)Beta](https://www.datacamp.com/zh/tutorial/exception-handling-python) *** [More Information](https://support.datacamp.com/hc/en-us/articles/21821832799255-Languages-Available-on-DataCamp) [Found an Error?]() [Log in](https://www.datacamp.com/users/sign_in?redirect=%2Ftutorial%2Fexception-handling-python)[Get Started](https://www.datacamp.com/users/sign_up?redirect=%2Ftutorial%2Fexception-handling-python) Tutorials [Blogs](https://www.datacamp.com/blog) [Tutorials](https://www.datacamp.com/tutorial) [docs](https://www.datacamp.com/doc) [Podcasts](https://www.datacamp.com/podcast) [Cheat Sheets](https://www.datacamp.com/cheat-sheet) [code-alongs](https://www.datacamp.com/code-along) [Newsletter](https://dcthemedian.substack.com/) Category Category Technologies Discover content by tools and technology [AI Agents](https://www.datacamp.com/tutorial/category/ai-agents)[AI News](https://www.datacamp.com/tutorial/category/ai-news)[Artificial Intelligence](https://www.datacamp.com/tutorial/category/ai)[AWS](https://www.datacamp.com/tutorial/category/aws)[Azure](https://www.datacamp.com/tutorial/category/microsoft-azure)[Business Intelligence](https://www.datacamp.com/tutorial/category/learn-business-intelligence)[ChatGPT](https://www.datacamp.com/tutorial/category/chatgpt)[Databricks](https://www.datacamp.com/tutorial/category/databricks)[dbt](https://www.datacamp.com/tutorial/category/dbt)[Docker](https://www.datacamp.com/tutorial/category/docker)[Excel](https://www.datacamp.com/tutorial/category/excel)[Generative AI](https://www.datacamp.com/tutorial/category/generative-ai)[Git](https://www.datacamp.com/tutorial/category/git)[Google Cloud Platform](https://www.datacamp.com/tutorial/category/google-cloud-platform)[Hugging Face](https://www.datacamp.com/tutorial/category/Hugging-Face)[Java](https://www.datacamp.com/tutorial/category/java)[Julia](https://www.datacamp.com/tutorial/category/julia)[Kafka](https://www.datacamp.com/tutorial/category/apache-kafka)[Kubernetes](https://www.datacamp.com/tutorial/category/kubernetes)[Large Language Models](https://www.datacamp.com/tutorial/category/large-language-models)[MongoDB](https://www.datacamp.com/tutorial/category/mongodb)[MySQL](https://www.datacamp.com/tutorial/category/mysql)[NoSQL](https://www.datacamp.com/tutorial/category/nosql)[OpenAI](https://www.datacamp.com/tutorial/category/OpenAI)[PostgreSQL](https://www.datacamp.com/tutorial/category/postgresql)[Power BI](https://www.datacamp.com/tutorial/category/power-bi)[PySpark](https://www.datacamp.com/tutorial/category/pyspark)[Python](https://www.datacamp.com/tutorial/category/python)[R](https://www.datacamp.com/tutorial/category/r-programming)[Scala](https://www.datacamp.com/tutorial/category/scala)[Snowflake](https://www.datacamp.com/tutorial/category/snowflake)[Spreadsheets](https://www.datacamp.com/tutorial/category/spreadsheets)[SQL](https://www.datacamp.com/tutorial/category/sql)[SQLite](https://www.datacamp.com/tutorial/category/sqlite)[Tableau](https://www.datacamp.com/tutorial/category/tableau) Category Topics Discover content by data science topics [AI for Business](https://www.datacamp.com/tutorial/category/ai-for-business)[Big Data](https://www.datacamp.com/tutorial/category/big-data)[Career Services](https://www.datacamp.com/tutorial/category/career-services)[Cloud](https://www.datacamp.com/tutorial/category/cloud)[Data Analysis](https://www.datacamp.com/tutorial/category/data-analysis)[Data Engineering](https://www.datacamp.com/tutorial/category/data-engineering)[Data Literacy](https://www.datacamp.com/tutorial/category/data-literacy)[Data Science](https://www.datacamp.com/tutorial/category/data-science)[Data Visualization](https://www.datacamp.com/tutorial/category/data-visualization)[DataLab](https://www.datacamp.com/tutorial/category/datalab)[Deep Learning](https://www.datacamp.com/tutorial/category/deep-learning)[Machine Learning](https://www.datacamp.com/tutorial/category/machine-learning)[MLOps](https://www.datacamp.com/tutorial/category/mlops)[Natural Language Processing](https://www.datacamp.com/tutorial/category/natural-language-processing)[Vector Databases](https://www.datacamp.com/tutorial/category/vector-databases) [Browse Courses](https://www.datacamp.com/courses-all) category 1. [Home](https://www.datacamp.com/) 2. [Tutorials](https://www.datacamp.com/tutorial) 3. [Python](https://www.datacamp.com/tutorial/category/python) # Exception & Error Handling in Python 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. Contents Updated Dec 12, 2024 · 11 min read Contents - [Errors in Python](https://www.datacamp.com/tutorial/exception-handling-python#errors-in-python-herei) - [Exceptions in Python](https://www.datacamp.com/tutorial/exception-handling-python#exceptions-in-python-wehav) - [Built-in Python Exceptions](https://www.datacamp.com/tutorial/exception-handling-python#built-in-python-exceptions-herei) - [Exception Handling with try, except, else, and finally](https://www.datacamp.com/tutorial/exception-handling-python#exception-handling-with-try,-except,-else,-and-finally-after) - [The try and except statement](https://www.datacamp.com/tutorial/exception-handling-python#the-try-and-except-statement%C2%A0-themo) - [The try with else clause](https://www.datacamp.com/tutorial/exception-handling-python#the-try-with-else-clause-wehav) - [The finally keyword in Python](https://www.datacamp.com/tutorial/exception-handling-python#the-finally-keyword-in-python-the<c) - [Nested Exception Handling in Python](https://www.datacamp.com/tutorial/exception-handling-python#nested-exception-handling-in-python-wenee) - [Modifying the divide function](https://www.datacamp.com/tutorial/exception-handling-python#modifying-the-divide-function-wehav) - [File editing example](https://www.datacamp.com/tutorial/exception-handling-python#file-editing-example-let%E2%80%99s) - [Raising Exceptions in Python](https://www.datacamp.com/tutorial/exception-handling-python#raising-exceptions-in-python-asapy) - [Raising value error example](https://www.datacamp.com/tutorial/exception-handling-python#raising-value-error-example-wecan) - [Raising exception example](https://www.datacamp.com/tutorial/exception-handling-python#raising-exception-example-wecan) - [Handling raised exception example](https://www.datacamp.com/tutorial/exception-handling-python#handling-raised-exception-example-wecan) - [What's New in Python 3.10 and 3.11 for Exception Handling?](https://www.datacamp.com/tutorial/exception-handling-python#what's-new-in-python-3.10-and-3.11-for-exception-handling?-somei) - [Conclusion](https://www.datacamp.com/tutorial/exception-handling-python#conclusion-<span) - [FAQs](https://www.datacamp.com/tutorial/exception-handling-python#faq) ## Training more people? Get your team access to the full DataCamp for business platform. [For Business](https://www.datacamp.com/business)For a bespoke solution [book a demo](https://www.datacamp.com/business/demo-2). ![try except else finally process in Python](https://images.datacamp.com/image/upload/v1677232088/Exception%20and%20error%20handling%20in%20Python.png) 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 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. 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](https://www.datacamp.com/datalab/new?_tag=template&template-key=community-python-exception-handling-python) 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. ``` return "DataCamp"Powered ByWas this AI assistant helpful? Yes No ``` ``` Powered ByWas this AI assistant helpful? Yes No ``` 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. ``` Powered ByWas this AI assistant helpful? Yes No ``` ``` Powered ByWas this AI assistant helpful? Yes No ``` ## Exceptions in Python We have encountered a `ZeroDivisionError` (Exception). We can handle it at runtime by using `try` and `except` blocks. ``` test = 1/0Powered ByWas this AI assistant helpful? Yes No ``` ``` Powered ByWas this AI assistant helpful? Yes No ``` `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. ``` y = testPowered ByWas this AI assistant helpful? Yes No ``` ``` Powered ByWas this AI assistant helpful? Yes No ``` ## Built-in Python Exceptions Here is the 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 zero. 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. You can find a complete list of errors and exceptions in Python by reading the [documentation](https://docs.python.org/3/library/exceptions.html). Learn about Python exceptions by taking our [Object-Oriented Programming in Python](https://www.datacamp.com/courses/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. 1. Run the code under the `try` statement. 2. 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. ![try except statement in Python](https://images.datacamp.com/image/upload/v1677232827/try%20and%20except%20in%20Python.png) #### **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. ``` Powered ByWas this AI assistant helpful? Yes No ``` ``` An exception has occurred!Powered ByWas this AI assistant helpful? Yes No ``` #### Multiple except statement example 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. ``` Powered ByWas this AI assistant helpful? Yes No ``` ``` You cannot divide a value with zeroPowered ByWas this AI assistant helpful? Yes No ``` #### 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 `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. ``` Powered ByWas this AI assistant helpful? Yes No ``` ``` Powered ByWas this AI assistant helpful? Yes No ``` ### The try with else clause 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. ![try with else clause in Python](https://images.datacamp.com/image/upload/v1677233590/try%20except%20else%20in%20Python.png) #### 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. ``` Powered ByWas this AI assistant helpful? Yes No ``` ``` Your answer is 0.3333333333333333Powered ByWas this AI assistant helpful? Yes No ``` #### IndexError with else example 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. ``` Powered ByWas this AI assistant helpful? Yes No ``` The list `x` has four values, and we will test them for the 6th and 2nd indexes. ``` Powered ByWas this AI assistant helpful? Yes No ``` - At *n=6*, the `IndexError` exception was raised, and we got to see the error default message “list index out of range.” - At *n=2*, no exception was raised, and the function printed the result which is under the `else` statement. ``` Powered ByWas this AI assistant helpful? Yes No ``` ### The finally keyword in Python The `finally` keyword in the `try`\-`except` block is always executed, irrespective of whether there is an exception or not. In simple words, the `finally` block of code is run after the `try`, `except` and `else` block is final. It is quite useful in cleaning up resources and closing the object, especially closing the files. ![finally keyword in Python](https://images.datacamp.com/image/upload/v1677233778/try%20except%20else%20finally%20in%20Python.png) The `divide` function is created to handle `ZeroDivisionError` exceptions and display the result when there are no exceptions. No matter what the outcome is, it will always run `finally` to print “Code by DataCamp” in green color. ``` Powered ByWas this AI assistant helpful? Yes No ``` In the first test, we are dividing 1 by 0, which should raise the `ZeroDivisionError` exception and print the message. As we can see, we have an additional line after the error message. ``` divide(1,0)Powered ByWas this AI assistant helpful? Yes No ``` ``` Powered ByWas this AI assistant helpful? Yes No ``` When we add valid input, it displays the result by executing `else` and `finally` blocking. ``` divide(3,4)Powered ByWas this AI assistant helpful? Yes No ``` ``` Powered ByWas this AI assistant helpful? Yes No ``` Instead of an integer, we have added a string as a second argument, which has raised an exception, that is different from `ZeroDivisionError`, with a different message. ``` divide(1,'g')Powered ByWas this AI assistant helpful? Yes No ``` ``` Powered ByWas this AI assistant helpful? Yes No ``` In all three scenarios, there is one thing in common. The code is always running the print function under the `finally` statement. If you are new to Python and want to code like a real programmer, try our [Python Programming](https://www.datacamp.com/tracks/python-programming) skill track. You will learn to write efficient code, Python functions, software engineering, unit testing, and object-oriented programming. ## Nested Exception Handling in Python We need nested exception handling when we are preparing the program to handle multiple exceptions in a sequence. For example, we can add another try-except block under the `else` statement. So, if the first statement does not raise an exception, check the second statement with the other half of the code. ### Modifying the divide function We have modified the `divide` function from the previous example and added a nested try-except block under the `else` statement. So, if there is no `AttributeError`, it will run the `else` and check the new code for the `ZeroDivisionError` exception. ``` Powered ByWas this AI assistant helpful? Yes No ``` In the first scenario, we provide the list of four values `x` and denominator 3. The script will add 50 to the list, divide the individual value in the list by 3, and display the result. ``` Powered ByWas this AI assistant helpful? Yes No ``` The function was successfully executed without raising any exceptions. ``` Powered ByWas this AI assistant helpful? Yes No ``` Instead of a list, we have provided an integer to the first argument, which has raised `AttributeError`. ``` divide(4,3)Powered ByWas this AI assistant helpful? Yes No ``` ``` Powered ByWas this AI assistant helpful? Yes No ``` In the last scenario, we have provided the list, but 0 is the second argument that has raised the `ZeroDivisionError` exception under the `else` statement. ``` divide(x,0)Powered ByWas this AI assistant helpful? Yes No ``` ``` Powered ByWas this AI assistant helpful? Yes No ``` ### File editing example Let’s look at more practical examples of loading the file, writing a text, and closing the file. The `file_editor()` function will: - Check the `FileNotFoundError` exception for the `open()` function. - If the outer exception is not raised, it will check for the `write()` function exception. - No matter what, after opening the file, it will close the file by running the `finally` statement. - If the outer try statement raises the exception, it will return the error message with an invalid file path. ``` Powered ByWas this AI assistant helpful? Yes No ``` In the first scenario, we provide the file path and the text. ``` Powered By ``` The outer exception is raised. ``` data.txt file is not found!!Powered ByWas this AI assistant helpful? Yes No ``` To resolve the file not found exception, we must create a file `data.txt` using the Linux `echo` command. ``` !echo "File by DataCamp" > "data.txt"Powered ByWas this AI assistant helpful? Yes No ``` ![file editing in Workspace](https://images.datacamp.com/image/upload/v1677234376/File%20editing%20in%20Python%20with%20Workspace.png) After that, rerun the `file_editor()` function. ``` file_editor(path,text)Powered ByWas this AI assistant helpful? Yes No ``` The inner exception is raised, as the `write()` function is not able to add the text. ``` Unable to write the data. Please add an append: 'a' or write: 'w' parameter to the open() function.Powered ByWas this AI assistant helpful? Yes No ``` To resolve this issue, we need to change the third line from `data = open(path)` to `data = open(path, 'a')`. It will allow us to append the new text to the file. After rerunning the function, we successfully added the text to the file. ``` file_editor(path,text)Powered ByWas this AI assistant helpful? Yes No ``` ![file editing screenshot in Workspace](https://images.datacamp.com/image/upload/v1677234490/Python%20file%20editing%20in%20Workspace.png) Nested exception handling is not recommended as it makes exception handling more complex; developers use multiple `try`\-`except` blocks to create simple sequential exception handling. **Note:** you can also add a nested `try`\-`except` block under the `try` or `except` statement. It just depends on your requirements. ## Raising Exceptions in Python As a Python developer, you can throw an exception if certain conditions are met. It allows you to interrupt the program based on your requirements. To throw an exception, we have to use the `raise` keyword followed by an exception name. ### Raising value error example We can simply raise exceptions by adding a raise keyword in the `if`/`else` statement. In the example, we raise the `ValueError` if the value exceeds 1,000. We have changed the value to 2,000, which has made the `if` statement `TRUE` and raised `ValueError` with the custom message. The custom error message helps you figure out the problem quickly. ``` Powered ByWas this AI assistant helpful? Yes No ``` ``` Powered ByWas this AI assistant helpful? Yes No ``` ### Raising exception example We can also raise any random built-in Python exception if the condition is met. In our case, we have raised a generic Exception with the error message. ``` Powered ByWas this AI assistant helpful? Yes No ``` ``` Powered ByWas this AI assistant helpful? Yes No ``` ### Handling raised exception example We can also create our custom exception and handle the exception by using the `try`\-`except` block. In the example, we have added a value error example under the `try` statement. So, how will it work? Instead of throwing the exception and terminating the program, it will display the error message we provided. ``` Powered ByWas this AI assistant helpful? Yes No ``` This type of exception handling helps us prepare for errors not covered by Python and are specific to your application requirement. ``` Please add a value lower than 1,000Powered ByWas this AI assistant helpful? Yes No ``` ## What's New in Python 3.10 and 3.11 for Exception Handling? Some important new developments have been added to newer Python versions like 3.10 and 3.11 since the blog post was originally written: **1\. Structural pattern matching in Python 3.10:** Python 3.10 introduced structural pattern matching, which can be used to handle exceptions more elegantly by matching error types in a `match` statement. This is particularly useful when dealing with multiple exception types in a more readable way. Example: ``` Powered By ``` **2\. Fine-grained error locations in tracebacks (Python 3.11):** Tracebacks in Python 3.11 now show precise error locations, making it easier to debug exceptions. - Before Python 3.11: ``` value = (1 + 2) * (3 / 0)Powered By ``` - Traceback: ``` ZeroDivisionError: division by zeroPowered By ``` - **Python 3.11:** Tracebacks pinpoint the exact sub-expression causing the exception: ``` Powered By ``` **3\. Exception groups and `except*` (Python 3.11):** Python 3.11 introduced exception groups to handle multiple exceptions in a single block using `except*`. This is useful for managing asynchronous code or scenarios where multiple exceptions might be raised. Example: ``` Powered By ``` **4\. `add_note` method for exceptions (Python 3.11):** Exceptions now have an `add_note()` method, which allows developers to add custom notes to exceptions for better debugging. Example: ``` Powered By ``` - Traceback: ``` Powered By ``` **5\. PEP 654: Better handling of nested exceptions:** With exception groups, nested exceptions are now easier to debug and handle, especially in complex workflows like multiprocessing or asynchronous tasks. ## Conclusion Both [unit testing](https://www.datacamp.com/tutorial/unit-testing-python) and exception handling are the core parts of Python programming that make your code production-ready and error-proof. In this tutorial, we have learned about exceptions and errors in Python and how to handle them. Furthermore, we have learned about complex nested try-except blocks and created custom exception blocks based on requirements. These tools and mechanisms are essential, but most of the work is done through simple `try` and `except` blocks. Where `try` looks for exceptions raised by the code and `except` handles those exceptions. If this is confusing and you don’t know where to start, complete our [Introduction to Functions in Python](https://www.datacamp.com/courses/introduction-to-functions-in-python) course to understand scoping, lambda functions, and error handling. You can also enroll in the [Python Programmer](https://www.datacamp.com/tracks/python-programmer) career track to gain career-building skills and become a professional Python developer. ## Learn Python From Scratch Master Python for data science and gain in-demand skills. [Start Learning for Free](https://www.datacamp.com/tracks/associate-data-scientist-in-python) ## FAQs ### What is the difference between an error and an exception in Python? An error in Python is typically a more severe problem that prevents the program from continuing, such as a syntax error, which indicates that the code structure is incorrect. An exception, on the other hand, is a condition that interrupts the program's normal flow but can be handled within the program using try-except blocks, allowing the program to continue executing. ### Can you catch multiple exceptions in a single try-except block? Yes, Python allows you to catch multiple exceptions in a single try-except block by using a tuple of exception types. For example: `except (TypeError, ValueError):`. This will handle either a `TypeError` or a `ValueError` in the same block. ### How can you create a custom exception in Python? You can create a custom exception by defining a new class that inherits from the built-in `Exception` class. For example: ``` Powered By ``` ### What is the purpose of the else block in a try-except structure? The `else` block is executed if the `try` block does not raise an exception. It is useful for code that should be run only if the `try` block succeeds, keeping the code clean and separating the error handling from the normal execution path. ### Why is the finally block important in exception handling? The `finally` block is always executed, regardless of whether an exception is raised or not. It is typically used for cleanup actions, such as closing files or releasing resources, to ensure that these actions are performed under all circumstances. ### How can you suppress exceptions in Python? You can suppress exceptions by using the `contextlib.suppress` context manager. It allows you to specify exception types that should be ignored. For example: ``` Powered By ``` ### What happens if an exception is not caught in a Python program? If an exception is not caught, it propagates up the call stack, and if it remains unhandled, it terminates the program, printing a traceback to the console that shows where the exception occurred. ### Can you re-raise an exception after catching it? Yes, you can re-raise an exception using the `raise` statement without arguments in an `except` block. This is useful when you want to log an error or perform some other actions before allowing the exception to propagate further. ### Is there a way to handle all exceptions in Python? While it's possible to catch all exceptions using a bare `except:` clause, it's generally not recommended because it can catch unexpected exceptions and make debugging difficult. It's better to catch specific exceptions or use `except Exception:` to avoid catching system-exiting exceptions like `SystemExit` and `KeyboardInterrupt`. ### How do you differentiate between a syntax error and runtime exceptions in terms of when they occur? Syntax errors are detected at compile time, meaning the Python interpreter catches these errors before the program starts executing. Runtime exceptions occur during program execution when the interpreter encounters an operation it cannot perform, such as dividing by zero or accessing a non-existent variable. *** Author [Abid Ali Awan](https://www.datacamp.com/portfolio/kingabzpro) As a certified data scientist, I am passionate about leveraging cutting-edge technology to create innovative machine learning applications. With a strong background in speech recognition, data analysis and reporting, MLOps, conversational AI, and NLP, I have honed my skills in developing intelligent systems that can make a real impact. In addition to my technical expertise, I am also a skilled communicator with a talent for distilling complex concepts into clear and concise language. As a result, I have become a sought-after blogger on data science, sharing my insights and experiences with a growing community of fellow data professionals. Currently, I am focusing on content creation and editing, working with large language models to develop powerful and engaging content that can help businesses and individuals alike make the most of their data. Topics [Python](https://www.datacamp.com/tutorial/category/python) *** [Abid Ali Awan](https://www.datacamp.com/portfolio/kingabzpro)Certified data scientist, passionate about building ML apps, blogging on data science, and editing. *** Topics [Python](https://www.datacamp.com/tutorial/category/python) ![Data Skills](https://media.datacamp.com/legacy/v1656516097/Data_Skills_e781b5bb13.jpg?w=256) [6 Python Best Practices for Better Code](https://www.datacamp.com/blog/python-best-practices-for-better-code) ![](https://media.datacamp.com/legacy/v1717010519/datarhys_an_absurdist_oil_painting_of_a_python_unlocking_a_larg_10cdfd37_9d3c_4714_a738_1930f23a9b23_c145ebd2aa.webp?w=256) [Python KeyError Exceptions and How to Fix Them](https://www.datacamp.com/tutorial/python-keyerror) [Unit Testing in Python Tutorial](https://www.datacamp.com/tutorial/unit-testing-python) [How to Use the assert Statement in Python](https://www.datacamp.com/tutorial/understanding-the-python-assert-statement) [if…elif…else in Python Tutorial](https://www.datacamp.com/tutorial/elif-statements-python) [30 Cool Python Tricks For Better Code With Examples](https://www.datacamp.com/tutorial/python-tips-examples) Learn more about Python with these courses\! Course ### [Introduction to Python](https://www.datacamp.com/courses/intro-to-python-for-data-science) 4 hr 6\.8M Master the basics of data analysis with Python in just four hours. This online course will introduce the Python interface and explore popular packages. [See Details](https://www.datacamp.com/courses/intro-to-python-for-data-science) [Start Course](https://www.datacamp.com/users/sign_up?redirect=%2Fcourses%2Fintro-to-python-for-data-science%2Fcontinue) Course ### [Intermediate Python](https://www.datacamp.com/courses/intermediate-python) 4 hr 1\.3M Level up your data science skills by creating visualizations using Matplotlib and manipulating DataFrames with pandas. [See Details](https://www.datacamp.com/courses/intermediate-python) [Start Course](https://www.datacamp.com/users/sign_up?redirect=%2Fcourses%2Fintermediate-python%2Fcontinue) Course ### [Introduction to Importing Data in Python](https://www.datacamp.com/courses/introduction-to-importing-data-in-python) 3 hr 333\.4K Learn to import data into Python from various sources, such as Excel, SQL, SAS and right from the web. [See Details](https://www.datacamp.com/courses/introduction-to-importing-data-in-python) [Start Course](https://www.datacamp.com/users/sign_up?redirect=%2Fcourses%2Fintroduction-to-importing-data-in-python%2Fcontinue) [See More](https://www.datacamp.com/category/python) Related ![Data Skills](https://media.datacamp.com/legacy/v1656516097/Data_Skills_e781b5bb13.jpg?w=750) [blog6 Python Best Practices for Better Code](https://www.datacamp.com/blog/python-best-practices-for-better-code) Discover the Python coding best practices for writing best-in-class Python scripts. [![Javier Canales Luna's photo](https://media.datacamp.com/legacy/v1662144771/Javier_Canales_Luna_90f858d375.jpg?w=48)](https://www.datacamp.com/portfolio/jcanalesluna) Javier Canales Luna 13 min ![](https://media.datacamp.com/legacy/v1717010519/datarhys_an_absurdist_oil_painting_of_a_python_unlocking_a_larg_10cdfd37_9d3c_4714_a738_1930f23a9b23_c145ebd2aa.webp?w=750) [TutorialPython KeyError Exceptions and How to Fix Them](https://www.datacamp.com/tutorial/python-keyerror) Learn key techniques such as exception handling and error prevention to handle the KeyError exception in Python effectively. [![Javier Canales Luna's photo](https://media.datacamp.com/legacy/v1662144771/Javier_Canales_Luna_90f858d375.jpg?w=48)](https://www.datacamp.com/portfolio/jcanalesluna) Javier Canales Luna [TutorialUnit Testing in Python Tutorial](https://www.datacamp.com/tutorial/unit-testing-python) Learn what unit testing is, why its important, and how you can implement it with the help of Python. [![Abid Ali Awan's photo](https://media.datacamp.com/legacy/v1658155691/Abid_Ali_Awan_415cc44670.jpg?w=48)](https://www.datacamp.com/portfolio/kingabzpro) Abid Ali Awan [TutorialHow to Use the assert Statement in Python](https://www.datacamp.com/tutorial/understanding-the-python-assert-statement) Implementing the assert statement in Python is straightforward: We use assert to test conditions and display a message if the condition is false. [![Amberle McKee's photo](https://media.datacamp.com/legacy/v1686323883/Amberle_Mc_Kee_6eeb507e3d.jpg?w=48)](https://www.datacamp.com/portfolio/dramberlemckee) Amberle McKee [Tutorialif…elif…else in Python Tutorial](https://www.datacamp.com/tutorial/elif-statements-python) Learn how you can create if…elif…else statements in Python. ![DataCamp Team's photo](https://media.datacamp.com/cms/logo-green.jpg?w=48) DataCamp Team [Tutorial30 Cool Python Tricks For Better Code With Examples](https://www.datacamp.com/tutorial/python-tips-examples) We've curated 30 cool Python tricks you could use to improve your code and develop your Python skills. [![Kurtis Pykes 's photo](https://media.datacamp.com/legacy/v1658156357/Kurtis_e60df9583d.jpg?w=48)](https://www.datacamp.com/portfolio/kurtispykes) Kurtis Pykes [See More](https://www.datacamp.com/tutorial/category/python) [See More](https://www.datacamp.com/tutorial/category/python) ## Grow your data skills with DataCamp for Mobile Make progress on the go with our mobile courses and daily 5-minute coding challenges. [Download on the App Store](https://datacamp.onelink.me/xztQ/45dozwue?deep_link_sub1=%7B%22src_url%22%3A%22https%3A%2F%2Fwww.datacamp.com%2Ftutorial%2Fexception-handling-python%22%7D)[Get it on Google Play](https://datacamp.onelink.me/xztQ/go2f19ij?deep_link_sub1=%7B%22src_url%22%3A%22https%3A%2F%2Fwww.datacamp.com%2Ftutorial%2Fexception-handling-python%22%7D) **Learn** [Learn Python](https://www.datacamp.com/blog/how-to-learn-python-expert-guide)[Learn AI](https://www.datacamp.com/blog/how-to-learn-ai)[Learn Power BI](https://www.datacamp.com/learn/power-bi)[Learn Data Engineering](https://www.datacamp.com/category/data-engineering)[Assessments](https://www.datacamp.com/signal)[Career Tracks](https://www.datacamp.com/tracks/career)[Skill Tracks](https://www.datacamp.com/tracks/skill)[Courses](https://www.datacamp.com/courses-all)[Data Science Roadmap](https://www.datacamp.com/blog/data-science-roadmap) **Data Courses** [Python Courses](https://www.datacamp.com/category/python)[R Courses](https://www.datacamp.com/category/r)[SQL Courses](https://www.datacamp.com/category/sql)[Power BI Courses](https://www.datacamp.com/category/power-bi)[Tableau Courses](https://www.datacamp.com/category/tableau)[Alteryx Courses](https://www.datacamp.com/category/alteryx)[Azure Courses](https://www.datacamp.com/category/azure)[AWS Courses](https://www.datacamp.com/category/aws)[Google Cloud Courses](https://www.datacamp.com/category/google-cloud)[Google Sheets Courses](https://www.datacamp.com/category/google-sheets)[Excel Courses](https://www.datacamp.com/category/excel)[AI Courses](https://www.datacamp.com/category/artificial-intelligence)[Data Analysis Courses](https://www.datacamp.com/category/data-analysis)[Data Visualization Courses](https://www.datacamp.com/category/data-visualization)[Machine Learning Courses](https://www.datacamp.com/category/machine-learning)[Data Engineering Courses](https://www.datacamp.com/category/data-engineering)[Probability & Statistics Courses](https://www.datacamp.com/category/probability-and-statistics) **DataLab** [Get Started](https://www.datacamp.com/datalab)[Pricing](https://www.datacamp.com/datalab/pricing)[Security](https://www.datacamp.com/datalab/security)[Documentation](https://datalab-docs.datacamp.com/) **Certification** [Certifications](https://www.datacamp.com/certification)[Data Scientist](https://www.datacamp.com/certification/data-scientist)[Data Analyst](https://www.datacamp.com/certification/data-analyst)[Data Engineer](https://www.datacamp.com/certification/data-engineer)[SQL Associate](https://www.datacamp.com/certification/sql-associate)[Power BI Data Analyst](https://www.datacamp.com/certification/data-analyst-in-power-bi)[Tableau Certified Data Analyst](https://www.datacamp.com/certification/data-analyst-in-tableau)[Azure Fundamentals](https://www.datacamp.com/certification/azure-fundamentals)[AI Fundamentals](https://www.datacamp.com/certification/ai-fundamentals) **Resources** [Resource Center](https://www.datacamp.com/resources)[Upcoming Events](https://www.datacamp.com/webinars)[Blog](https://www.datacamp.com/blog)[Code-Alongs](https://www.datacamp.com/code-along)[Tutorials](https://www.datacamp.com/tutorial)[Docs](https://www.datacamp.com/doc)[Open Source](https://www.datacamp.com/open-source)[RDocumentation](https://www.rdocumentation.org/)[Book a Demo with DataCamp for Business](https://www.datacamp.com/business/demo)[Data Portfolio](https://www.datacamp.com/data-portfolio) **Plans** [Pricing](https://www.datacamp.com/pricing)[For Students](https://www.datacamp.com/pricing/student)[For Business](https://www.datacamp.com/business)[For Universities](https://www.datacamp.com/universities)[Discounts, Promos & Sales](https://www.datacamp.com/promo)[Expense DataCamp](https://www.datacamp.com/expense)[DataCamp Donates](https://www.datacamp.com/donates) **For Business** [Business Pricing](https://www.datacamp.com/business/compare-plans)[Teams Plan](https://www.datacamp.com/business/learn-teams)[Data & AI Unlimited Plan](https://www.datacamp.com/business/data-unlimited)[Customer Stories](https://www.datacamp.com/business/customer-stories)[Partner Program](https://www.datacamp.com/business/partner-program) **About** [About Us](https://www.datacamp.com/about)[Learner Stories](https://www.datacamp.com/stories)[Careers](https://www.datacamp.com/careers)[Become an Instructor](https://www.datacamp.com/learn/create)[Press](https://www.datacamp.com/press)[Leadership](https://www.datacamp.com/about/leadership)[Contact Us](https://support.datacamp.com/hc/en-us/articles/360021185634)[DataCamp Español](https://www.datacamp.com/es)[DataCamp Português](https://www.datacamp.com/pt)[DataCamp Deutsch](https://www.datacamp.com/de)[DataCamp Français](https://www.datacamp.com/fr) **Support** [Help Center](https://support.datacamp.com/hc/en-us)[Become an Affiliate](https://www.datacamp.com/affiliates) [Facebook](https://www.facebook.com/datacampinc/) [Twitter](https://twitter.com/datacamp) [LinkedIn](https://www.linkedin.com/school/datacampinc/) [YouTube](https://www.youtube.com/channel/UC79Gv3mYp6zKiSwYemEik9A) [Instagram](https://www.instagram.com/datacamp/) [Privacy Policy](https://www.datacamp.com/privacy-policy)[Cookie Notice](https://www.datacamp.com/cookie-notice)[Do Not Sell My Personal Information](https://www.datacamp.com/do-not-sell-my-personal-information)[Accessibility](https://www.datacamp.com/accessibility)[Security](https://www.datacamp.com/security)[Terms of Use](https://www.datacamp.com/terms-of-use) © 2026 DataCamp, Inc. All Rights Reserved.
Readable Markdown
![try except else finally process in Python](https://images.datacamp.com/image/upload/v1677232088/Exception%20and%20error%20handling%20in%20Python.png) 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 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. 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](https://www.datacamp.com/datalab/new?_tag=template&template-key=community-python-exception-handling-python) 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 using `try` and `except` blocks. `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. Built-in Python Exceptions 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](https://docs.python.org/3/library/exceptions.html). Learn about Python exceptions by taking our [Object-Oriented Programming in Python](https://www.datacamp.com/courses/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. ![try except statement in Python](https://images.datacamp.com/image/upload/v1677232827/try%20and%20except%20in%20Python.png) **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. Multiple except statement example 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. 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 `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. The try with else clause 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. ![try with else clause in Python](https://images.datacamp.com/image/upload/v1677233590/try%20except%20else%20in%20Python.png) 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. IndexError with else example 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. The list `x` has four values, and we will test them for the 6th and 2nd indexes. At *n=6*, the `IndexError` exception was raised, and we got to see the error default message “list index out of range.” At *n=2*, no exception was raised, and the function printed the result which is under the `else` statement. The finally keyword in Python The `finally` keyword in the `try`\-`except` block is always executed, irrespective of whether there is an exception or not. In simple words, the `finally` block of code is run after the `try`, `except` and `else` block is final. It is quite useful in cleaning up resources and closing the object, especially closing the files. ![finally keyword in Python](https://images.datacamp.com/image/upload/v1677233778/try%20except%20else%20finally%20in%20Python.png) The `divide` function is created to handle `ZeroDivisionError` exceptions and display the result when there are no exceptions. No matter what the outcome is, it will always run `finally` to print “Code by DataCamp” in green color. In the first test, we are dividing 1 by 0, which should raise the `ZeroDivisionError` exception and print the message. As we can see, we have an additional line after the error message. When we add valid input, it displays the result by executing `else` and `finally` blocking. Instead of an integer, we have added a string as a second argument, which has raised an exception, that is different from `ZeroDivisionError`, with a different message. In all three scenarios, there is one thing in common. The code is always running the print function under the `finally` statement. If you are new to Python and want to code like a real programmer, try our [Python Programming](https://www.datacamp.com/tracks/python-programming) skill track. You will learn to write efficient code, Python functions, software engineering, unit testing, and object-oriented programming. Nested Exception Handling in Python We need nested exception handling when we are preparing the program to handle multiple exceptions in a sequence. For example, we can add another try-except block under the `else` statement. So, if the first statement does not raise an exception, check the second statement with the other half of the code. Modifying the divide function We have modified the `divide` function from the previous example and added a nested try-except block under the `else` statement. So, if there is no `AttributeError`, it will run the `else` and check the new code for the `ZeroDivisionError` exception. In the first scenario, we provide the list of four values `x` and denominator 3. The script will add 50 to the list, divide the individual value in the list by 3, and display the result. The function was successfully executed without raising any exceptions. Instead of a list, we have provided an integer to the first argument, which has raised `AttributeError`. In the last scenario, we have provided the list, but 0 is the second argument that has raised the `ZeroDivisionError` exception under the `else` statement. File editing example Let’s look at more practical examples of loading the file, writing a text, and closing the file. The `file_editor()` function will: Check the `FileNotFoundError` exception for the `open()` function. If the outer exception is not raised, it will check for the `write()` function exception. No matter what, after opening the file, it will close the file by running the `finally` statement. If the outer try statement raises the exception, it will return the error message with an invalid file path. In the first scenario, we provide the file path and the text. The outer exception is raised. To resolve the file not found exception, we must create a file `data.txt` using the Linux `echo` command. ![file editing in Workspace](https://images.datacamp.com/image/upload/v1677234376/File%20editing%20in%20Python%20with%20Workspace.png) After that, rerun the `file_editor()` function. The inner exception is raised, as the `write()` function is not able to add the text. To resolve this issue, we need to change the third line from `data = open(path)` to `data = open(path, 'a')`. It will allow us to append the new text to the file. After rerunning the function, we successfully added the text to the file. ![file editing screenshot in Workspace](https://images.datacamp.com/image/upload/v1677234490/Python%20file%20editing%20in%20Workspace.png) Nested exception handling is not recommended as it makes exception handling more complex; developers use multiple `try`\-`except` blocks to create simple sequential exception handling. **Note:** you can also add a nested `try`\-`except` block under the `try` or `except` statement. It just depends on your requirements. Raising Exceptions in Python As a Python developer, you can throw an exception if certain conditions are met. It allows you to interrupt the program based on your requirements. To throw an exception, we have to use the `raise` keyword followed by an exception name. Raising value error example We can simply raise exceptions by adding a raise keyword in the `if`/`else` statement. In the example, we raise the `ValueError` if the value exceeds 1,000. We have changed the value to 2,000, which has made the `if` statement `TRUE` and raised `ValueError` with the custom message. The custom error message helps you figure out the problem quickly. Raising exception example We can also raise any random built-in Python exception if the condition is met. In our case, we have raised a generic Exception with the error message. Handling raised exception example We can also create our custom exception and handle the exception by using the `try`\-`except` block. In the example, we have added a value error example under the `try` statement. So, how will it work? Instead of throwing the exception and terminating the program, it will display the error message we provided. This type of exception handling helps us prepare for errors not covered by Python and are specific to your application requirement. What's New in Python 3.10 and 3.11 for Exception Handling? Some important new developments have been added to newer Python versions like 3.10 and 3.11 since the blog post was originally written: **1\. Structural pattern matching in Python 3.10:** Python 3.10 introduced structural pattern matching, which can be used to handle exceptions more elegantly by matching error types in a `match` statement. This is particularly useful when dealing with multiple exception types in a more readable way. Example: **2\. Fine-grained error locations in tracebacks (Python 3.11):** Tracebacks in Python 3.11 now show precise error locations, making it easier to debug exceptions. Before Python 3.11: Traceback: **Python 3.11:** Tracebacks pinpoint the exact sub-expression causing the exception: **3\. Exception groups and `except*` (Python 3.11):** Python 3.11 introduced exception groups to handle multiple exceptions in a single block using `except*`. This is useful for managing asynchronous code or scenarios where multiple exceptions might be raised. Example: **4\. `add_note` method for exceptions (Python 3.11):** Exceptions now have an `add_note()` method, which allows developers to add custom notes to exceptions for better debugging. Example: Traceback: **5\. PEP 654: Better handling of nested exceptions:** With exception groups, nested exceptions are now easier to debug and handle, especially in complex workflows like multiprocessing or asynchronous tasks. Conclusion Both [unit testing](https://www.datacamp.com/tutorial/unit-testing-python) and exception handling are the core parts of Python programming that make your code production-ready and error-proof. In this tutorial, we have learned about exceptions and errors in Python and how to handle them. Furthermore, we have learned about complex nested try-except blocks and created custom exception blocks based on requirements. These tools and mechanisms are essential, but most of the work is done through simple `try` and `except` blocks. Where `try` looks for exceptions raised by the code and `except` handles those exceptions. If this is confusing and you don’t know where to start, complete our [Introduction to Functions in Python](https://www.datacamp.com/courses/introduction-to-functions-in-python) course to understand scoping, lambda functions, and error handling. You can also enroll in the [Python Programmer](https://www.datacamp.com/tracks/python-programmer) career track to gain career-building skills and become a professional Python developer.
Shard136 (laksa)
Root Hash7979813049800185936
Unparsed URLcom,datacamp!www,/tutorial/exception-handling-python s443