🕷️ Crawler Inspector

URL Lookup

Direct Parameter Lookup

Raw Queries and Responses

1. Shard Calculation

Query:
Response:
Calculated Shard: 76 (from laksa171)

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.scholarhat.com/tutorial/python/exception-handling-in-python
Last Crawled2026-04-15 14:31:13 (2 days ago)
First Indexed2023-03-16 09:41:25 (3 years ago)
HTTP Status Code200
Meta TitleException Handling in Python: Try and Except Statement
Meta DescriptionDiscover Python exception handling with examples, including Try and Except, specific exceptions, Else clause, Finally keyword, and raising exceptions, plus pros and cons.
Meta Canonicalnull
Boilerpipe Text
Exception Handling in Python is an essential concept that helps you manage and control runtime errors, known as exceptions, ensuring your program runs smoothly without unexpected crashes. Python provides the try, except, else, and finally blocks to handle exceptions effectively. Common exceptions include ZeroDivisionError, TypeError, ValueError, and FileNotFoundError . In this Python tutorial , we explore how exception handling works in Python with examples. Whether you're a beginner or an experienced developer, this guide will help you write error-free and robust Python programs.  Python developers earn up to 50% more than average coders. Don’t miss out Enroll in our Free Online Python Course   today! What is Exception Handling? Exception handling is a technique in Python that deals with errors that occur during program execution. It entails spotting potential error situations, responding appropriately to exceptions when they arise, and identifying possible error conditions. Using the try and except keywords, Python provides a structured approach to exception handling. By the end of this tutorial, you will gain a through understanding of: The concept of exceptions and why they occur in Python The difference between syntax errors and exceptions How to use try, except, else, and finally blocks for handling exceptions Catching specific exceptions vs. using a generic exception handler Raising exceptions manually using the raise keyword Using the assert statement for debugging and error handling Different Types of Exceptions in Python: Various built-in Python exceptions can be thrown when an error occurs during program execution. Here are some of the most popular types of Python exceptions: SyntaxError: When the interpreter comes across a syntactic problem in the code, such as a misspelled word, a missing colon, or an unbalanced pair of parentheses, this exception is raised. Example: TypeError: When an operation or function is done to an object of the incorrect type, such as by adding a string to an integer, an exception is thrown. NameError: When a variable or function name cannot be found in the current scope, the exception NameError is thrown. IndexError: This exception is thrown when a list , tuple , or other sequence type's index is outside of bounds. KeyError: When a key cannot be found in a dictionary, this exception is thrown. ValueError: This exception is thrown when an invalid argument or input is passed to a function or method. An example would be trying to convert a string to an integer when the string does not represent a valid integer. AttributeError: When an attribute or method is not present on an object, such as when attempting to access a non-existent attribute of a class instance, the exception AttributeError is thrown. IOError: This exception is thrown if an input/output error occurs during an I/O operation, such as reading or writing to a file. ZeroDivisionError: This exception is thrown whenever a division by zero is attempted. ImportError: This exception is thrown whenever a module cannot be loaded or found by an import statement. FileNotFoundError: FileNotFoundError occurs when trying to open a file that does not exist. ModuleNotFoundError: ModuleNotFoundError occurs when trying to import a module that is not installed or does not exist. BaseException: The parent class for all built-in exceptions. Exception: The superclass for all non-exit exceptions. Understanding try, except, else, and finally Blocks in Python 1. try Block This block contains the code that might cause an error. If an error occurs, Python immediately jumps to the except block 2. except Block This block catches and handles the error if one occurs in the try block. We can specify different types of exceptions or use a general one. 3. else Block Runs only if no exception occurs in the try block. Useful when you want to execute some code only when there is no error. 4. finally Block Runs no matter what happens, whether there is an exception or not. Useful for cleanup tasks (e.g., closing a file or database connection). Syntax of Exception Handling in Python This is the basic syntax of a Try-Catch block in python. try: # Code that might raise an exception risky_operation() except SpecificException as e: # Code that runs if a specific exception occurs print(f"An error occurred: {e}") except AnotherException: # Handle another specific type of exception handle_it() except Exception as e: # General exception handler (catches all exceptions not caught above) print(f"General error: {e}") else: # Code that runs **only if no exception was raised** print("Operation succeeded without any error.") finally: # Code that always runs, regardless of what happened above print("Cleaning up resources...") Differences Between try and except in Python Feature Errors Exceptions Definition Serious issues that stop the program from running Issues that occur during execution but can be handled Causes Syntax mistakes, missing modules, incorrect indentation Incorrect input, division by zero, file not found, etc. Handling Cannot be handled using try-except Can be handled using try-except Examples SyntaxError, IndentationError, MemoryError ZeroDivisionError, FileNotFoundError, KeyError Difference Between Exception and Error Feature Exception Error Definition An exception is an event that occurs during program execution and disrupts the normal flow of instructions. An error is a serious issue in the program that prevents it from continuing execution. Recoverability Can be handled using try-except blocks. Generally, errors are unrecoverable and should be fixed in the code. Causes Caused by logical mistakes, invalid user input, or unforeseen conditions. Caused by system failures, memory overflow, or hardware limitations. Examples ZeroDivisionError, IndexError, KeyError, FileNotFoundError MemoryError, StackOverflowError, OutOfMemoryError, SystemError Handling Can be caught and handled by the program. It cannot be caught easily and usually requires fixing the underlying issue. Try and Except Statement – Catching Exceptions In Python, you may catch and deal with exceptions by using the try and except commands. The try and except clauses are used to contain statements that can raise exceptions and statements that handle such exceptions. Exception handling in Python helps to manage errors in a program. With exception handling in Python, you can prevent your code from crashing. Example of Try and Except Statement in Python try : number = int ( input ( "Enter a number: " )) result = 10 / number print ( "The result is:" , result) except ZeroDivisionError: print ( "Division by zero is not allowed." ) except ValueError: print ( "Invalid input. Please enter a valid number." ) In this example in the Python Editor , the try block attempts to divide 10 by the input entered by the user. The result is calculated and reported if the input is a valid integer that is not zero. If the input is invalid (for example, a string ) or zero, the corresponding except block raises an exception and displays an appropriate error message. Output Enter a number: 0 Division by zero is not allowed. Catching Specific Exception To provide handlers for various exceptions, a try statement may contain more than one except clause. Please be aware that only one handler will be run at a time. Exception handling in Python uses try and except blocks to catch errors. Debugging becomes easier with exception handling in Python. Example of Catching Specific Exception in Python try : file = open ( "test.txt" , "r" ) contents = file.read() print (contents) file.close() except FileNotFoundError: print ( "File not found." ) except IOError: print ( "An error occurred while reading the file." ) This code will attempt to open the file "test.txt" and read its contents. The code will print an error message if the file is not found. If an error occurs while reading the file, the code will display an error message before proceeding to the next line of code. Output File not found. Try with Else Clause Python additionally allows the use of an else clause on a try-except block, which must come after every except clause. Only when the try clause fails to throw an exception does the code go on to the else block . Using exception handling in Python, you can write safer and more reliable programs. Example of Try with Else Clause in Python try : # Open a file named "test.txt" for reading file = open ( "test.txt" , "r" ) # Read the contents of the file contents = file.read() # Close the file file.close() # Check if the contents of the file contain the word "Python" if "Python" in contents: # If the word "Python" is found, print a message print ( "The word 'Python' is found in the file." ) else : # If the word "Python" is not found, print a message print ( "The word 'Python' is not found in the file." ) except FileNotFoundError: # If the file "test.txt" is not found, print an error message print ( "The file 'test.txt' could not be found." ) else : # If no exceptions occur, print a message print ( "The file 'test.txt' was successfully read." ) A try block is used in this example to read "test.txt" and look for the word "Python." If the file access is successful, the otherwise block is executed. If an exception occurs, such as FileNotFoundError, the error is handled by the associated except block. Output The file 'test.txt' could not be found. Finally Keyword in Python The final keyword in Python is always used after the try and except blocks. The try block normally terminates once the final block executes, or after the try block quits because of an exception. Example of Finally Keyword in Python def divide_numbers ( a, b ): try : result = a / b except ZeroDivisionError: print ( "Error: Cannot divide by zero!" ) else : print ( f"The result of {a} divided by {b} is: {result} " ) finally : print ( "This block always executes, regardless of exceptions." ) divide_numbers( 10 , 2 ) divide_numbers( 5 , 0 ) The code defines the function divide_numbers, which attempts to divide two numbers, prints the result if successful, handles the division by zero exception, and ensures that a final block of code (finally) always executes, regardless of whether an exception occurred or not. Output The result of 10 divided by 2 is: 5.0 This block always executes, regardless of exceptions. Error: Cannot divide by zero! This block always executes, regardless of exceptions. Catch-All Handlers and Their Risks Unintended Exception Handling: Catching all exceptions (except Exception:) may suppress critical errors, making debugging difficult. Hidden Bugs: Swallowing exceptions without proper logging can obscure the root cause of issues. Example of Catch-All Handlers and Their Risks in Python def risky_operation (): raise ValueError( "An unexpected error occurred." ) try : risky_operation() except Exception as e: # Catch-all handler print ( "An error occurred:" , e) # Risk: This might hide critical issues Output An error occurred: An unexpected error occurred. Catching Multiple Exceptions Handling Specific Errors : Catching multiple exceptions allows handling different error types separately. Better Debugging: Helps identify the exact cause of failure rather than using a generic catch-all handler. Example of Catching Multiple Exceptions in Python def safe_divide ( a, b ): if b == 0 : raise ZeroDivisionError( "Cannot divide by zero." ) return a / b try : num1, num2 = map ( int , input ( "Enter two numbers: " ).split()) result = safe_divide(num1, num2) print ( "The result is:" , result) except ZeroDivisionError as e: print ( "Error:" , e) except ValueError as e: print ( "Invalid input. Please enter numbers only." ) Output Enter two numbers: 10 0 Error: Cannot divide by zero. Raise an Exception The raise statement enables the programmer to compel the occurrence of a particular exception. Raise's lone argument specifies the exception that should be raised. Either an exception instance or an exception class (a class deriving from Exception) must be present here. Example of Raising Exception in Python def divide ( a, b ): if b == 0 : raise ZeroDivisionError( "Cannot divide by zero." ) return a / b try : result = divide( 10 , 2 ) print ( "The result is:" , result) except ZeroDivisionError as e: print ( "Error:" , e) The code in the Python Compiler implements a divide function to conduct division, throwing a ZeroDivisionError if the divisor is 0. It then attempts to call this method, prints the result if successful, and throws an exception if division by zero happens. Output The result is: 5.0 New Features in Exception Handling in Python 3.10 and 3.11 Feature Python 3.10 Python 3.11 Clearer Error Messages Error messages became easier to understand. Error messages are now even more helpful — they point to the exact part of the code that caused the issue. SyntaxError: '(' was never closed Shows arrows like --> divide(x, y) so you know exactly where it broke. Pattern Matching for Errors You can match errors using match-case , like matching puzzle pieces. match err: case FileNotFoundError(): print("File error") Same in 3.11 — just as useful. Handle Many Errors Together Not possible. New in 3.11! You can catch multiple errors at once using except* . except* ValueError: print("Handled group") Faster Exception Handling No speed improvements. Running try-except blocks is now around 10–15% faster. Python 3.10 Better Error Messages : Syntax errors now provide clearer and more specific messages, making debugging easier. Pattern Matching for Exceptions : A new way to handle exceptions using structural pattern matching, making code more readable and organized. Python 3.11 Faster Exception Handling:  Performance improvements make exception handling up to 10-15% faster. More Detailed Tracebacks : Tracebacks now highlight the exact line and expression where the error occurred, improving debugging. Exception Groups: Allows multiple exceptions to be raised and handled together, useful for concurrent and batch processing. Advantages of Exception Handling Increased program dependability: By managing exceptions correctly, you can stop your program from crashing or generating wrong results because of unforeseen faults or input. Error handling made easier: It is simpler to comprehend and maintain your code when you can separate the error management code from the core program logic using exception handling. Simpler coding: With exception handling, you can write code that is clearer and easier to comprehend by avoiding the use of intricate conditional expressions to check for mistakes. Simpler debugging: When an exception is raised, the Python interpreter generates a traceback that identifies the precise place in your code where the error happened. Disadvantages of Exception Handling Performance penalty: Because the interpreter must undertake an extra effort to detect and handle the exception, exception handling can be slower than utilizing conditional statements to check for mistakes. Code complexity increase: Handling exceptions can make your code more difficult, especially if you have to deal with a variety of exception types or use sophisticated error-handling logic. Possible security risks: It's critical to manage exceptions carefully and avoid disclosing too much information about your program because improperly handled exceptions may reveal sensitive information or lead to security flaws in your code. Summary In this article, we have understood that Exception handling is and important concept in Python. It ensures that any mistake or unforeseen input does not cause the program to crash. Exception handling can be used to check both syntax levels and validations accordingly. Only 5% of Python coders become full-stack experts. Be one of them with our Full-Stack Python Developer Certification Training . Enroll today to lead, not follow! Python Exception Handling Quiz Q 1: What is the purpose of the try-except block in Python? To handle exceptions To define functions To iterate over lists To declare variables FAQs The "ZeroDivisionError" that occurs when dividing by zero is an illustration of an exception in Python. User-defined exceptions and built-in exceptions, such as ValueError and IndexError, are the two basic categories of exceptions in Python. Python's "try" and "except" blocks are used to handle exceptions. An exception explicitly relates to runtime defects that may be caught and handled in Python, whereas an error is a broader phrase that refers to mistakes in code. Take our Python skill challenge to evaluate yourself! In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill. GET FREE CHALLENGE
Markdown
[![Logo](https://www.scholarhat.com/dist/user/assets/logo-CEy3TSwt.png)ScholarHat](https://www.scholarhat.com/) [Live Training]() [All Live Trainings](https://www.scholarhat.com/training) ### Training Categories ![.NET Platform](https://dotnettrickscloud.blob.core.windows.net/uploads/CourseImages/netplatform-mobile.png) .NET Platform ![AI/ML & Gen AI](https://dotnettrickscloud.blob.core.windows.net/uploads/CourseImages/aimlgenai-mobile.png) AI/ML & Gen AI ![Career & Leadership](https://dotnettrickscloud.blob.core.windows.net/uploads/CourseImages/careerleadership-mobile.png) Career & Leadership ![Cloud & DevOps](https://dotnettrickscloud.blob.core.windows.net/uploads/CourseImages/clouddevops-mobile.png) Cloud & DevOps ![Java Platform](https://dotnettrickscloud.blob.core.windows.net/uploads/CourseImages/javaplatform-mobile.png) Java Platform ![JS & Front-end](https://dotnettrickscloud.blob.core.windows.net/uploads/CourseImages/jsfrontend-mobile.png) JS & Front-end ### Category Name Live sessions with industry experts [![.NET AI & ML Engineer Certification Training](https://dotnettrickscloud.blob.core.windows.net/uploads/CourseImages/aimlcertificationtrainingfornetdevelopers-mobile.png) .NET AI & ML Engineer Certification Training Build Intelligent AI/ML-Driven Solutions with ML.NET](https://www.scholarhat.com/training/net-ai-ml-certification-training) [![.NET Certification Training](https://dotnettrickscloud.blob.core.windows.net/uploads/CourseImages/netcertificationtraining-mobile.png) .NET Certification Training Master C\# & SQL Server from basic to advanced](https://www.scholarhat.com/training/net-certification-training) [![.NET Microservices Certification Training](https://dotnettrickscloud.blob.core.windows.net/uploads/CourseImages/netmicroservicescertificationtraining-mobile.png) .NET Microservices Certification Training Build scalable microservices using .NET & Docker/K8s](https://www.scholarhat.com/training/net-microservices-certification-training) [![.NET Software Architecture and Design Training](https://dotnettrickscloud.blob.core.windows.net/uploads/CourseImages/netsoftwarearchitectureanddesigntraining-mobile.png) .NET Software Architecture and Design Training Design clean, maintainable, enterprise-grade architectures](https://www.scholarhat.com/training/software-architecture-design-training) [![ASP.NET Core Certification Training](https://dotnettrickscloud.blob.core.windows.net/uploads/CourseImages/aspnetcorecertificationtraining-mobile.png) ASP.NET Core Certification Training Build fast web apps using ASP.NET Core, EF & Web API](https://www.scholarhat.com/training/aspnet-core-certification-training) [![Blazor Certification Training](https://dotnettrickscloud.blob.core.windows.net/uploads/CourseImages/blazorserver-mobile.png) Blazor Certification Training Build interactive web apps using C\# & Razor](https://www.scholarhat.com/training/blazor-certification-training) #### Join Live Sessions Learn with experts in real-time [Join Now](https://www.scholarhat.com/training/batches) [Job-Ready Tracks]() [All Job-Ready Tracks](https://www.scholarhat.com/job-oriented) ### Training Categories ![.NET](https://dotnettrickscloud.blob.core.windows.net/uploads/CourseImages/net-mobile.png) .NET ![AI/ML](https://dotnettrickscloud.blob.core.windows.net/uploads/CourseImages/aiml-mobile.png) AI/ML ![Java](https://dotnettrickscloud.blob.core.windows.net/uploads/CourseImages/java-mobile.png) Java ### .NET Roles-based Live training programs [![.NET & Azure Solution Architect Program](https://dotnettrickscloud.blob.core.windows.net/uploads/CourseImages/microsoftazurecloudarchitect-mobile.png) .NET & Azure Solution Architect Program Master Azure, System Design & Microservices Architecture](https://www.scholarhat.com/job-oriented/net-azure-solution-architect-certification-training) [![AI-Driven .NET Tech Lead Program](https://dotnettrickscloud.blob.core.windows.net/uploads/CourseImages/aidrivenazurefullstacknettechleadcertificationprogram-mobile.png) AI-Driven .NET Tech Lead Program Master ASP.NET Core, Angular/React, AI/ML with Azure](https://www.scholarhat.com/job-oriented/net-tech-lead-certification-training) [![AI-Powered Full-Stack .NET Developer Program](https://dotnettrickscloud.blob.core.windows.net/uploads/CourseImages/fullstacknetdevelopercertificationtrainingcourse-mobile.png) AI-Powered Full-Stack .NET Developer Program Master AI, ASP.NET Core with Angular or React](https://www.scholarhat.com/job-oriented/full-stack-net-developer-certification-training) #### Start Your Career Job-ready tracks [Explore](https://www.scholarhat.com/training/batches) [LIVE Batches](https://www.scholarhat.com/training/batches) [FREE Masterclasses](https://www.scholarhat.com/master-classes) [FREE Courses/Books]() [Free Courses](https://www.scholarhat.com/free-course) [Free Books](https://www.scholarhat.com/books) [Skill Tests](https://www.scholarhat.com/skill-tests) [Sandboxes]() [Cloud Sandboxes](https://www.scholarhat.com/sandbox) [Practice DSA](https://www.scholarhat.com/problems) [Explore]() [Membership](https://www.scholarhat.com/membership/live) [Online Compiler](https://www.scholarhat.com/compiler) [Skill Tests](https://www.scholarhat.com/skill-tests) [Tutorial](https://www.scholarhat.com/tutorial) [Reviews](https://www.scholarhat.com/reviews) [0](https://www.scholarhat.com/cart) [Login/SignUp](https://www.scholarhat.com/login) Live Training ![.NET Platform](https://dotnettrickscloud.blob.core.windows.net/uploads/CourseImages/netplatform-mobile.png) .NET Platform ![AI/ML & Gen AI](https://dotnettrickscloud.blob.core.windows.net/uploads/CourseImages/aimlgenai-mobile.png) AI/ML & Gen AI ![Career & Leadership](https://dotnettrickscloud.blob.core.windows.net/uploads/CourseImages/careerleadership-mobile.png) Career & Leadership ![Cloud & DevOps](https://dotnettrickscloud.blob.core.windows.net/uploads/CourseImages/clouddevops-mobile.png) Cloud & DevOps ![Java Platform](https://dotnettrickscloud.blob.core.windows.net/uploads/CourseImages/javaplatform-mobile.png) Java Platform ![JS & Front-end](https://dotnettrickscloud.blob.core.windows.net/uploads/CourseImages/jsfrontend-mobile.png) JS & Front-end [All Live Trainings](https://www.scholarhat.com/training) Job Ready Tracks ![.NET](https://dotnettrickscloud.blob.core.windows.net/uploads/CourseImages/net-mobile.png) .NET ![AI/ML](https://dotnettrickscloud.blob.core.windows.net/uploads/CourseImages/aiml-mobile.png) AI/ML ![Java](https://dotnettrickscloud.blob.core.windows.net/uploads/CourseImages/java-mobile.png) Java [All Job-Ready Tracks](https://www.scholarhat.com/job-oriented) [Free Master Classes](https://www.scholarhat.com/master-classes) Free Courses / Books [Free Courses](https://www.scholarhat.com/free-course) [Free Books](https://www.scholarhat.com/books) [Skill Assessments](https://www.scholarhat.com/skill-tests) Sandboxes [Cloud Sandboxes](https://www.scholarhat.com/sandbox) [Practice DSA](https://www.scholarhat.com/problems) [Training Batches](https://www.scholarhat.com/training/batches) Explore [Membership](https://www.scholarhat.com/membership/live) [DSA Problems](https://www.scholarhat.com/problems) [Online Compiler](https://www.scholarhat.com/compiler) [Skill Assessments](https://www.scholarhat.com/skill-tests) [Reviews](https://www.scholarhat.com/Reviews) [Tutorials](https://www.scholarhat.com/tutorial) [Login/SignUp](https://www.scholarhat.com/login) [Live Batches](https://www.scholarhat.com/training/batches) [Masterclasses](https://www.scholarhat.com/master-classes) Menu [Free Courses](https://www.scholarhat.com/free-course) Account [Login / Sign Up](https://www.scholarhat.com/Account/Login) Toggle Theme Browse Tutorials ## [Cheat Sheet]() [Python Cheat Sheet: Full Guide Beginners 41 min](https://www.scholarhat.com/tutorial/python/python-cheat-sheet "Get More Details") ## [Python Basic]() [How to Learn Python for Data Science: A Complete Guide Beginners 16 min](https://www.scholarhat.com/tutorial/python/how-to-learn-python-for-data-science "Get More Details") [Python Recursion: Types of Recursion in Python Beginners 25 min](https://www.scholarhat.com/tutorial/python/recursion-in-python-a-detailed-explanation "Get More Details") [Calculation of Armstrong Number in Python Beginners 32 min](https://www.scholarhat.com/tutorial/python/armstrong-number-in-python "Get More Details") [Understanding Python While Loop with Examples Beginners 20 min](https://www.scholarhat.com/tutorial/python/python-while-loop "Get More Details") [Python Programming Examples Beginners 6 min](https://www.scholarhat.com/tutorial/python/python-programming-examples "Get More Details") [What is Python Language? Overview of the Python Language Beginners 9 min](https://www.scholarhat.com/tutorial/python/overview-of-the-python-language "Get More Details") [Python Basic Syntax: First Python Program Beginners 13 min](https://www.scholarhat.com/tutorial/python/the-basic-syntax-of-python "Get More Details") [Comments in Python -Types, How to Write, Uses Beginners 22 min](https://www.scholarhat.com/tutorial/python/comments-used-in-the-python-language "Get More Details") [What are Python Variables - Types of Variables in Python Language Beginners 33 min](https://www.scholarhat.com/tutorial/python/variables-of-python "Get More Details") [Data Types in Python - 8 Data Types in Python With Examples Beginners 30 min](https://www.scholarhat.com/tutorial/python/data-types-in-python "Get More Details") [Python Classes and Objects with Examples Intermediate 14 min](https://www.scholarhat.com/tutorial/python/python-classes-and-objects "Get More Details") [What are Strings in Python? Learn to Implement Them. Intermediate 15 min](https://www.scholarhat.com/tutorial/python/strings-in-python "Get More Details") [10 Reasons Python is a Great First Language to Learn Career 6 min](https://www.scholarhat.com/tutorial/python/10-reasons-python-is-great-language-to-learn "Get More Details") ## [Basics]() [Libraries in Python-A Complete Resolution Beginners 27 min](https://www.scholarhat.com/tutorial/python/libraries-in-python-a-complete-resolution "Get More Details") [Fibonacci Series in Python -Explained with Examples Beginners 14 min](https://www.scholarhat.com/tutorial/python/fibonacci-series-in-python "Get More Details") [Python Design Patterns - Basics to Advanced (2025 Guide) Beginners 24 min](https://www.scholarhat.com/tutorial/python/python-design-patterns "Get More Details") [What Are Modules in Python? Definition, Basics, and Examples Intermediate 23 min](https://www.scholarhat.com/tutorial/python/modules-in-python "Get More Details") ## [Roadmaps]() [How to Become a Python Full Stack Developer \[Step-by-Step\] Career 21 min](https://www.scholarhat.com/tutorial/python/python-full-stack-developer "Get More Details") ## [Python Fundamentals]() [Data Structures in Python: A Complete Guide with Types and Examples Beginners 53 min](https://www.scholarhat.com/tutorial/python/data-structures-in-python "Get More Details") [Python Program to Check Prime Number Beginners 22 min](https://www.scholarhat.com/tutorial/python/python-prime-number "Get More Details") [Program to Check Leap Year in Python Beginners 14 min](https://www.scholarhat.com/tutorial/python/program-to-check-leap-year-in-python "Get More Details") [Factorial Calculator in Python Beginners 17 min](https://www.scholarhat.com/tutorial/python/factorial-in-python "Get More Details") [What is a Python Interpreter? Beginners 6 min](https://www.scholarhat.com/tutorial/python/interpreter-in-python "Get More Details") [How to Run a Python Script- A Step by Step Guide Beginners 9 min](https://www.scholarhat.com/tutorial/python/run-a-python-script "Get More Details") [Arithmetic Operators in Python Beginners 15 min](https://www.scholarhat.com/tutorial/python/arithmetic-operators-in-python "Get More Details") [Difference between For Loop and While Loop in Python Beginners 9 min](https://www.scholarhat.com/tutorial/python/difference-between-for-and-while-loop-in-python "Get More Details") [The enumerate() Function in Python Beginners 11 min](https://www.scholarhat.com/tutorial/python/enumerate-in-python "Get More Details") [An Easy Way To Understanding Python Slicing Beginners 26 min](https://www.scholarhat.com/tutorial/python/slicing-in-python "Get More Details") [Introduction to the python language Beginners 7 min](https://www.scholarhat.com/tutorial/python/introduction-to-the-python-language "Get More Details") [What are Operators in Python - Types of Operators in Python ( With Examples ) Beginners 22 min](https://www.scholarhat.com/tutorial/python/operators-of-python "Get More Details") [Python Dictionaries (With Examples) : A Comprehensive Tutorial Intermediate 12 min](https://www.scholarhat.com/tutorial/python/dictionary-in-python "Get More Details") [Exception Handling in Python: Try and Except Statement Intermediate 28 min](https://www.scholarhat.com/tutorial/python/exception-handling-in-python "Get More Details") ## [Keywords]() [How Many Keyword in Python (With Examples) Beginners 25 min](https://www.scholarhat.com/tutorial/python/keywords-in-python "Get More Details") ## [Data Types]() [Logical Operators Python Beginners 9 min](https://www.scholarhat.com/tutorial/python/logical-operators-python "Get More Details") ## [Operators in Python]() [Addition of Two Numbers in Python Beginners 9 min](https://www.scholarhat.com/tutorial/python/program-to-add-two-numbers-in-python "Get More Details") [Comparison Operators Python Beginners 11 min](https://www.scholarhat.com/tutorial/python/comparison-operators-python "Get More Details") [Essential Python Full-Stack Developer Skills You Need to Master in 2025 Beginners 13 min](https://www.scholarhat.com/tutorial/python/python-full-stack-developer-skills "Get More Details") [Bitwise Operators in Python: Types and Examples Beginners 14 min](https://www.scholarhat.com/tutorial/python/bitwise-operators-in-python "Get More Details") [Python Membership Operators: Types of Membership Operators Beginners 6 min](https://www.scholarhat.com/tutorial/python/python-membership-operators "Get More Details") [Operators in Python Intermediate 11 min](https://www.scholarhat.com/tutorial/python/types-of-operators-examples "Get More Details") [10 Python Developer Skills you must know in 2025 Career 21 min](https://www.scholarhat.com/tutorial/python/python-developer-skills "Get More Details") ## [Conditional Statements]() [Decision Making Statements: If, If..else, Nested If..else and if-elif-else Ladder Beginners 12 min](https://www.scholarhat.com/tutorial/python/decision-making-statements-if-else-nested-if-else "Get More Details") ## [Control Flow and Loops]() [Python Developer Salary Career 13 min](https://www.scholarhat.com/tutorial/python/python-developer-salary "Get More Details") ## [Loops]() [If Else Statement In Python Beginners 14 min](https://www.scholarhat.com/tutorial/python/if-else-statement-in-python "Get More Details") [Python For Loop: Syntax, Examples & Best Practice Beginners 15 min](https://www.scholarhat.com/tutorial/python/python-for-loop "Get More Details") [Types of Loops in Python - For, While Loop Beginners 14 min](https://www.scholarhat.com/tutorial/python/while-for-nested-loop "Get More Details") ## [Functions and Libraries]() [Swapping Numbers in Python Beginners 12 min](https://www.scholarhat.com/tutorial/python/swap-two-numbers-in-python "Get More Details") [The map() Function in Python Beginners 21 min](https://www.scholarhat.com/tutorial/python/map-function-in-python "Get More Details") [What is Python Functions - Types of Python Functions (With Examples) Beginners 26 min](https://www.scholarhat.com/tutorial/python/functions-in-the-python-language "Get More Details") [Python Career Guide: Is it worth learning in 2025? Career 8 min](https://www.scholarhat.com/tutorial/python/python-career-opportunities "Get More Details") [Python Roadmap: How to become a Python Developer? Career 11 min](https://www.scholarhat.com/tutorial/python/python-developer-roadmap "Get More Details") ## [Lambda Function]() [Lambda Function in Python with Examples (Full Tutorial) Beginners 15 min](https://www.scholarhat.com/tutorial/python/lambda-function-in-python "Get More Details") ## [Python String]() [How to Reverse a String in Python Beginners 9 min](https://www.scholarhat.com/tutorial/python/reverse-a-string-in-python "Get More Details") ## [Slicing]() [Sort in Python- An Easy Way to Learn Beginners 17 min](https://www.scholarhat.com/tutorial/python/sorting-in-python-an-easy-way-to-learn "Get More Details") ## [Python List]() [Inheritance In Python Beginners 27 min](https://www.scholarhat.com/tutorial/python/inheritance-in-python "Get More Details") [Assignment Operators in Python Beginners 16 min](https://www.scholarhat.com/tutorial/python/assignment-operators-in-python "Get More Details") [How to Use List Comprehension in Python Intermediate 35 min](https://www.scholarhat.com/tutorial/python/python-list-comprehension "Get More Details") [What is List In Python: Learn List in Python (With Example) Intermediate 34 min](https://www.scholarhat.com/tutorial/python/list-in-python "Get More Details") ## [Python Tuples]() [Tuples in Python with Examples - A Beginner Guide Beginners 29 min](https://www.scholarhat.com/tutorial/python/tuples-in-python "Get More Details") ## [Python File Handling]() [File Handling In Python: Python File Operations Beginners 21 min](https://www.scholarhat.com/tutorial/python/python-file-handling "Get More Details") ## [OOPs]() [Oops Concepts in Python With Examples (Full Tutorial) Intermediate 16 min](https://www.scholarhat.com/tutorial/python/oops-concepts-in-python "Get More Details") ## [contructors]() [Understanding Constructors in Python Beginners 26 min](https://www.scholarhat.com/tutorial/python/constructors-in-python "Get More Details") ## [AI Fundamentals]() [Learn AI with Python:Beginner Guide Beginners 14 min](https://www.scholarhat.com/tutorial/python/python-and-ai "Get More Details") ## [Career]() [How to Learn Python (Step-By-Step) in 2025 Beginners 18 min](https://www.scholarhat.com/tutorial/python/how-to-learn-python-step-by-step "Get More Details") ## [Interview]() [Top 50 Python Data Science Interview Questions and Answers Beginners 45 min](https://www.scholarhat.com/tutorial/python/python-data-science-interview-questions "Get More Details") [Top 50+ Python Interview Questions and Answers Questions 80 min](https://www.scholarhat.com/tutorial/python/python-interview-questions-and-answers "Get More Details") ## [Python Interview Questions]() [Python Features: A Comprehensive Guide for Beginners Beginners 16 min](https://www.scholarhat.com/tutorial/python/features-of-python-programming-language "Get More Details") [Python MCQ \| Python Multiple Choice Questions with Answers Intermediate 124 min](https://www.scholarhat.com/tutorial/python/python-mcq "Get More Details") [Python Viva Interview Questions For Freshers Questions 72 min](https://www.scholarhat.com/tutorial/python/python-viva-questions "Get More Details") 1. [Home](https://www.scholarhat.com/) 2. [Tutorials](https://www.scholarhat.com/tutorial) 3. [Python](https://www.scholarhat.com/tutorial/python) 4. Exception Handling In Pyt.. ![Exception Handling in Python: Try and Except Statement ](https://dotnettrickscloud.blob.core.windows.net/article/5020250311231708.png) # Exception Handling in Python: Try and Except Statement 11 Sep 2025 Intermediate 20\.2K Views 28 min read ![](https://dotnettrickscloud.blob.core.windows.net/uploads/CourseImages/pythonprogrammingcourse-mobile.png) Learn with an interactive course and practical hands-on labs ### Free Python Programming Course For Beginners [![](https://www.scholarhat.com/images/icons/freecourse.svg) Start Learning Free](https://www.scholarhat.com/free-course/python-course-for-beginners?utm_source=Scholarhat&utm_medium=Article&utm_campaign=Free_Course&utm_content=https://www.scholarhat.com/tutorial/python/exception-handling-in-python) [![](https://www.scholarhat.com/images/icons/freecourse.svg) Free Interview books](https://www.scholarhat.com/books/python-interview-questions-and-answers-book-pdf) [![](https://www.scholarhat.com/images/icons/test.svg) Skill Test](https://www.scholarhat.com/skill-test/python) **Exception Handling in Python** is an essential concept that helps you manage and control runtime errors, known as exceptions, ensuring your program runs smoothly without unexpected crashes. Python provides the **try, except, else, and finally** blocks to handle exceptions effectively. Common exceptions include **ZeroDivisionError, TypeError, ValueError, and FileNotFoundError**. In this [Python tutorial](https://www.scholarhat.com/tutorial/python-exception-handling), we explore **how exception handling works in Python** with examples. Whether you're a beginner or an experienced developer, this guide will help you write error-free and robust Python programs. **Python developers earn up to 50% more than average coders. Don’t miss out Enroll in our** [Free Online Python Course](https://www.scholarhat.com/free-course/python-course-for-beginners) **today\!** ## What is Exception Handling? Exception handling is a technique in Python that deals with errors that occur during program execution.It entails spotting potential error situations, responding appropriately to exceptions when they arise, and identifying possible error conditions.Using the try and except keywords, Python provides a structured approach to exception handling. **By the end of this tutorial, you will gain a through understanding of:** - The concept of exceptions and why they occur in Python - The difference between syntax errors and exceptions - How to use try, except, else, and finally blocks for handling exceptions - Catching specific exceptions vs. using a generic exception handler - Raising exceptions manually using the raise keyword - Using the assert statement for debugging and error handling ![exception handling in python](https://dotnettrickscloud.blob.core.windows.net/article/python/5020250308183720.webp) | | |---| | **Read More: [Data Science with Python Certification Course](https://www.scholarhat.com/training/data-science-with-python-certification-training#:~:text=Data%20Science%20with%20Python%20training,proficient%20data%20scientist%20using%20Python.)** | ## Different Types of Exceptions in Python: Various built-in Python exceptions can be thrown when an error occurs during program execution. Here are some of the most popular types of Python exceptions: 1. **SyntaxError:** When the interpreter comes across a syntactic problem in the code, such as a misspelled word, a missing colon, or an unbalanced pair of parentheses, this exception is raised. Example: 2. **TypeError:** When an operation or function is done to an object of the incorrect type, such as by adding a [string](https://www.scholarhat.com/tutorial/python/strings-in-python) to an integer, an exception is thrown. 3. **NameError:** When a [variable](https://www.scholarhat.com/tutorial/python/variables-of-python) or function name cannot be found in the current scope, the exception NameError is thrown. 4. **IndexError:** This exception is thrown when a [list](https://www.scholarhat.com/tutorial/python/list-in-python), [tuple](https://www.scholarhat.com/tutorial/python/tuples-in-python), or other sequence type's index is outside of bounds. 5. **KeyError:** When a key cannot be found in a dictionary, this exception is thrown. 6. **ValueError:** This exception is thrown when an invalid argument or input is passed to a [function](https://www.scholarhat.com/tutorial/python/functions-in-the-python-language) or method. An example would be trying to convert a string to an integer when the string does not represent a valid integer. 7. **AttributeError:** When an attribute or method is not present on an object, such as when attempting to access a non-existent attribute of a class instance, the exception AttributeError is thrown. 8. **IOError:** This exception is thrown if an input/output error occurs during an I/O operation, such as reading or writing to a file. 9. **ZeroDivisionError:** This exception is thrown whenever a division by zero is attempted. 10. **ImportError:** This exception is thrown whenever a module cannot be loaded or found by an import statement. 11. **FileNotFoundError:**FileNotFoundError occurs when trying to open a file that does not exist. 12. **ModuleNotFoundError:**ModuleNotFoundError occurs when trying to import a module that is not installed or does not exist. 13. **BaseException:**The parent class for all built-in exceptions. 14. **Exception:**The superclass for all non-exit exceptions. | | |---| | **Read More: [Python Interview Questions and Answers](https://www.scholarhat.com/tutorial/python/python-interview-questions-and-answers)** | ## Understanding try, except, else, and finally Blocks in Python ## 1\. try Block - This block contains the code that might cause an error. - If an error occurs, Python immediately jumps to the except block ### 2\. except Block - This block catches and handles the error if one occurs in the try block. - We can specify different types of exceptions or use a general one. ### 3\. else Block - Runs only if no exception occurs in the try block. - Useful when you want to execute some code only when there is no error. ### 4\. finally Block - Runs no matter what happens, whether there is an exception or not. - Useful for cleanup tasks (e.g., closing a file or database connection). | | |---| | **Read More: [Python Viva Interview Questions](https://www.scholarhat.com/tutorial/interview/python-viva-questions)** | ## Syntax of Exception Handling in Python ``` This is the basic syntax of a Try-Catch block in python. ``` ## Differences Between try and except in Python | | | | |---|---|---| | Feature | Errors | Exceptions | | Definition | Serious issues that stop the program from running | Issues that occur during execution but can be handled | | Causes | Syntax mistakes, missing modules, incorrect indentation | Incorrect input, division by zero, file not found, etc. | | Handling | Cannot be handled using **try-except** | Can be handled using try-except | | Examples | **SyntaxError, IndentationError, MemoryError** | **ZeroDivisionError, FileNotFoundError, KeyError** | Difference Between Exception and Error | | | | |---|---|---| | **Feature** | **Exception** | **Error** | | **Definition** | An exception is an event that occurs during program execution and disrupts the normal flow of instructions. | An error is a serious issue in the program that prevents it from continuing execution. | | **Recoverability** | Can be handled using try-except blocks. | Generally, errors are unrecoverable and should be fixed in the code. | | **Causes** | Caused by logical mistakes, invalid user input, or unforeseen conditions. | Caused by system failures, memory overflow, or hardware limitations. | | **Examples** | **ZeroDivisionError, IndexError, KeyError, FileNotFoundError** | **MemoryError, StackOverflowError, OutOfMemoryError, SystemError** | | **Handling** | Can be caught and handled by the program. | It cannot be caught easily and usually requires fixing the underlying issue. | Try and Except Statement – Catching Exceptions - In Python, you may catch and deal with exceptions by using the try and except commands. - The try and except clauses are used to contain statements that can raise exceptions and statements that handle such exceptions. - Exception handling in Python helps to manage errors in a program. - With exception handling in Python, you can prevent your code from crashing. ## ## Example of Try and Except Statement in Python ``` ``` In this example in the [**Python Editor**](https://www.scholarhat.com/compiler/python), the try block attempts to divide 10 by the input entered by the user. The result is calculated and reported if the input is a valid integer that is not zero. If the input is invalid (for example, [a string](https://www.scholarhat.com/tutorial/python/strings-in-python)) or zero, the corresponding except block raises an exception and displays an appropriate error message. #### Output ``` Enter a number: 0 Division by zero is not allowed. ``` ## ## Catching Specific Exception - To provide handlers for various exceptions, a try statement may contain more than one except clause. - Please be aware that only one handler will be run at a time. - Exception handling in Python uses try and except blocks to catch errors. - Debugging becomes easier with exception handling in Python. ## Example of Catching Specific Exception in Python ``` ``` Run Code \>\> This code will attempt to open the file "test.txt" and read its contents. The code will print an error message if the file is not found. If an error occurs while reading the file, the code will display an error message before proceeding to the next line of code. #### Output ``` File not found. ``` | | |---| | **Read More: [Python Developer Salary](https://www.scholarhat.com/tutorial/python/python-developer-salary)** | Try with Else Clause - Python additionally allows the use of an else clause on a try-except block, which must come after every except clause. - Only when the try clause fails to throw an exception does the code go on to the [else block](https://www.scholarhat.com/tutorial/python/decision-making-statements-if-else-nested-if-else). - Using exception handling in Python, you can write safer and more reliable programs. Example of Try with Else Clause in Python ``` ``` Run Code \>\> A try block is used in this example to read "test.txt" and look for the word "Python." If the file access is successful, the otherwise block is executed. If an exception occurs, such as FileNotFoundError, the error is handled by the associated except block. #### Output ``` The file 'test.txt' could not be found. ``` ## ## Finally Keyword in Python - The final[keyword in Python](https://www.scholarhat.com/tutorial/python/keywords-in-python)is always used after the try and except blocks. - The try block normally terminates once the final block executes, or after the try block quits because of an exception. ## Example of Finally Keyword in Python ``` ``` Run Code \>\> The code defines the [function](https://www.scholarhat.com/tutorial/python/functions-in-the-python-language) divide\_numbers, which attempts to divide two numbers, prints the result if successful, handles the division by zero exception, and ensures that a final block of code (finally) always executes, regardless of whether an exception occurred or not. #### Output ``` The result of 10 divided by 2 is: 5.0 This block always executes, regardless of exceptions. Error: Cannot divide by zero! This block always executes, regardless of exceptions. ``` ## ## Catch-All Handlers and Their Risks - **Unintended Exception Handling:**Catching all exceptions (except Exception:) may suppress critical errors, making debugging difficult. - **Hidden Bugs:**Swallowing exceptions without proper logging can obscure the root cause of issues. ### Example of Catch-All Handlers and Their Risks in Python ``` ``` Run Code \>\> #### Output ``` An error occurred: An unexpected error occurred. ``` ## ##### ## Catching Multiple Exceptions - **Handling Specific Errors**: Catching multiple exceptions allows handling different error types separately. - **Better Debugging:**Helps identify the exact cause of failure rather than using a generic catch-all handler. ### Example of Catching Multiple Exceptions in Python ``` def safe_divide(a, b): if b == 0: raise ZeroDivisionError("Cannot divide by zero.") return a / b try: num1, num2 = map(int, input("Enter two numbers: ").split()) result = safe_divide(num1, num2) print("The result is:", result) except ZeroDivisionError as e: print("Error:", e) except ValueError as e: print("Invalid input. Please enter numbers only.") ``` Run Code \>\> #### Output ``` Enter two numbers: 10 0 Error: Cannot divide by zero. ``` ## ## Raise an Exception - The raise statement enables the programmer to compel the occurrence of a particular exception. - Raise's lone argument specifies the exception that should be raised. - Either an exception instance or an exception class (a class deriving from Exception) must be present here. ## Example of Raising Exception in Python ``` ``` Run Code \>\> The code in the [**Python Compiler**](https://www.scholarhat.com/compiler/python) implements a divide [function](https://www.scholarhat.com/tutorial/python/functions-in-the-python-language) to conduct division, throwing a ZeroDivisionError if the divisor is 0. It then attempts to call this method, prints the result if successful, and throws an exception if division by zero happens. #### Output ``` The result is: 5.0 ``` ## ##### ## New Features in Exception Handling in Python 3.10 and 3.11 | | | | |---|---|---| | Feature | Python 3.10 | Python 3.11 | | Clearer Error Messages | Error messages became easier to understand. | Error messages are now even more helpful — they point to the exact part of the code that caused the issue. `SyntaxError: '(' was never closed` Shows arrows like `--> divide(x, y)` so you know exactly where it broke. | | Pattern Matching for Errors | You can match errors using `match-case`, like matching puzzle pieces. `match err: case FileNotFoundError(): print("File error")` | Same in 3.11 — just as useful. | | Handle Many Errors Together | Not possible. | New in 3.11! You can catch multiple errors at once using `except*`. `except* ValueError: print("Handled group")` | | Faster Exception Handling | No speed improvements. | Running try-except blocks is now around 10–15% faster. | ### Python 3.10 - **Better Error Messages**: Syntax errors now provide clearer and more specific messages, making debugging easier. - **Pattern Matching for Exceptions**: A new way to handle exceptions using structural pattern matching, making code more readable and organized. ### Python 3.11 - **Faster Exception Handling:** Performance improvements make exception handling up to 10-15% faster. - **More Detailed Tracebacks :**Tracebacks now highlight the exact line and expression where the error occurred, improving debugging. - **Exception Groups:**Allows multiple exceptions to be raised and handled together, useful for concurrent and batch processing. Advantages of Exception Handling - **Increased program dependability:** By managing exceptions correctly, you can stop your program from crashing or generating wrong results because of unforeseen faults or input. - **Error handling made easier:** It is simpler to comprehend and maintain your code when you can separate the error management code from the core program logic using exception handling. - **Simpler coding:** With exception handling, you can write code that is clearer and easier to comprehend by avoiding the use of intricate conditional expressions to check for mistakes. - **Simpler debugging:** When an exception is raised, the [Python interpreter](https://www.scholarhat.com/tutorial/python/interpreter-in-python) generates a traceback that identifies the precise place in your code where the error happened. ## Disadvantages of Exception Handling - **Performance penalty:** Because the interpreter must undertake an extra effort to detect and handle the exception, exception handling can be slower than utilizing conditional statements to check for mistakes. - **Code complexity increase:** Handling exceptions can make your code more difficult, especially if you have to deal with a variety of exception types or use sophisticated error-handling logic. - **Possible security risks:** It's critical to manage exceptions carefully and avoid disclosing too much information about your program because improperly handled exceptions may reveal sensitive information or lead to security flaws in your code. #### Summary In this article, we have understood that Exception handling is and important concept in Python. It ensures that any mistake or unforeseen input does not cause the program to crash. Exception handling can be used to check both syntax levels and validations accordingly. **Only 5% of Python coders become full-stack experts. Be one of them with our [Full-Stack Python Developer Certification Training](https://www.scholarhat.com/job-oriented/full-stack-python-developer-certification-training). Enroll today to lead, not follow\!** #### Q 1: What is the purpose of the try-except block in Python? - To handle exceptions - To define functions - To iterate over lists - To declare variables Previous Next ### FAQs ### Q1. What is an example of an exception in Python? The "ZeroDivisionError" that occurs when dividing by zero is an illustration of an exception in Python. ### Q2. What are the two main types of exceptions? User-defined exceptions and built-in exceptions, such as ValueError and IndexError, are the two basic categories of exceptions in Python. ### Q3. Which class is used for exception handling? Python's "try" and "except" blocks are used to handle exceptions. ### Q4. What is the difference between an error and an exception? An exception explicitly relates to runtime defects that may be caught and handled in Python, whereas an error is a broader phrase that refers to mistakes in code. ## Take our Python skill challenge to evaluate yourself\! ![]() In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill. [GET FREE CHALLENGE](https://www.scholarhat.com/skill-test/python?utm_source=Scholarhat&utm_medium=Article&utm_campaign=Get_Free_Challange&utm_term=https://www.scholarhat.com/tutorial/python/exception-handling-in-python) **Share Article** Similar Articles - [**Python Design Patterns - Basics to Advanced (2025 Guide)**](https://www.scholarhat.com/tutorial/python/python-design-patterns) - [**Learn AI with Python:Beginner Guide**](https://www.scholarhat.com/tutorial/python/python-and-ai) - [**Libraries in Python-A Complete Resolution**](https://www.scholarhat.com/tutorial/python/libraries-in-python-a-complete-resolution) - [**Addition of Two Numbers in Python**](https://www.scholarhat.com/tutorial/python/program-to-add-two-numbers-in-python) - [**How to Learn Python (Step-By-Step) in 2025**](https://www.scholarhat.com/tutorial/python/how-to-learn-python-step-by-step) - [**How to Become a Python Full Stack Developer \[Step-by-Step\]**](https://www.scholarhat.com/tutorial/python/python-full-stack-developer) [**![](https://www.scholarhat.com/images/icons/previous.svg) Previous Tutorial**What Are Modules in Python? Definition, Basics, and Examples](https://www.scholarhat.com/tutorial/python/modules-in-python) [**Next Tutorial ![](https://www.scholarhat.com/images/icons/next.svg)**Python Viva Interview Questions For Freshers](https://www.scholarhat.com/tutorial/python/python-viva-questions) ###### About Author ![Author image](https://dotnettrickscloud.blob.core.windows.net/uploads/mentorImages/2820240301224200.png) [View Profile](https://www.scholarhat.com/mentors/sakshi-dhameja) Sakshi Dhameja (Author and Mentor) *** She is passionate about different technologies like JavaScript, React, HTML, CSS, Node.js etc. and likes to share knowledge with the developer community. She holds strong learning skills in keeping herself updated with the changing technologies in her area as well as other technologies like Core Java, Python and Cloud. Our Courses [![Azure AI & Gen AI Engineer Certification Training]() Azure AI & Gen AI Engineer Certification Training Master Azure AI with our Azure AI Engineer Course. Prepare for the AI-102 exam through hands-on Azure AI Engineer Certification Training and boost your career in AI. View More](https://www.scholarhat.com/training/azure-ai-engineer-certification-training?utm_source=training_programs&utm_medium=text&utm_campaign=https://www.scholarhat.com/tutorial/python/exception-handling-in-python "Azure AI & Gen AI Engineer Certification Training") [![Python For Data Science and AI/ML Certification Training]() Python For Data Science and AI/ML Certification Training The Python Certification Course offers a comprehensive learning experience for individuals looking to master the Python programming language and its versatile applications. View More](https://www.scholarhat.com/training/python-data-science-ai-certification-training?utm_source=training_programs&utm_medium=text&utm_campaign=https://www.scholarhat.com/tutorial/python/exception-handling-in-python "Python For Data Science and AI/ML Certification Training") ##### Live Training - Book Free Demo ![](https://dotnettrickscloud.blob.core.windows.net/uploads/CourseImages/azureaiengineercertificationtraining-mobile.png) ###### Azure AI & Gen AI Engineer Certification Training 19 Apr • 05:30PM - 07:30PM IST Get Job-Ready • Certification [TRY FREE DEMO](https://www.scholarhat.com/training/azure-ai-engineer-certification-training?utm_source=Scholarhat&utm_medium=Article&utm_campaign=Live_Class_Schedule&utm_term=/tutorial/python/exception-handling-in-python) Free Master Classes 17 Apr Become a Multi-Cloud AI Engineer: Build, Train & Deploy AI Systems [Register Now](https://www.scholarhat.com/master-classes/build-train-deploy-ai-systems-multi-cloud?utm_source=Scholarhat&utm_medium=Article&utm_campaign=Upcoming_Master_Class&utm_content=https://www.scholarhat.com/tutorial/python/exception-handling-in-python) 25 Apr Build & Deploy Your First AI App with Python, Azure & AWS [Register Now](https://www.scholarhat.com/master-classes/build-and-deploy-ai-systems-multi-cloud?utm_source=Scholarhat&utm_medium=Article&utm_campaign=Upcoming_Master_Class&utm_content=https://www.scholarhat.com/tutorial/python/exception-handling-in-python) 26 Apr Java Microservices in Production: Spring Boot to AWS Deployment [Register Now](https://www.scholarhat.com/master-classes/java-solution-architect?utm_source=Scholarhat&utm_medium=Article&utm_campaign=Upcoming_Master_Class&utm_content=https://www.scholarhat.com/tutorial/python/exception-handling-in-python) 26 Apr From Monolith to Microservices: Scalable Architecture with .NET, Azure & Kubernetes [Register Now](https://www.scholarhat.com/master-classes/monolith-to-micro-services-architecture?utm_source=Scholarhat&utm_medium=Article&utm_campaign=Upcoming_Master_Class&utm_content=https://www.scholarhat.com/tutorial/python/exception-handling-in-python) ![](https://www.scholarhat.com/images/logo_sm.png) LEAD-ACE: EdTech Platform 100% Live Sessions ![](https://www.scholarhat.com/images/icons/note.svg) 600+ Quick notes ![](https://www.scholarhat.com/images/icons/lab.svg) 900+ Hands-on labs ![](https://www.scholarhat.com/images/icons/project.svg) 50+ Real-world projects ![](https://www.scholarhat.com/images/icons/question.svg) 45+ Interview books #### Job Ready Tracks [.NET & Azure Solution Architect Program](https://www.scholarhat.com/job-oriented/net-azure-solution-architect-certification-training) \| [AI-Driven .NET Tech Lead Program](https://www.scholarhat.com/job-oriented/net-tech-lead-certification-training) \| [AI-Driven Java Tech Lead Program](https://www.scholarhat.com/job-oriented/java-tech-lead-certification-training) \| [AI-Powered Full-Stack .NET Developer Program](https://www.scholarhat.com/job-oriented/full-stack-net-developer-certification-training) \| [Azure AI Architect Program](https://www.scholarhat.com/job-oriented/azure-ai-architect-certification-training) \| [Multi-Cloud AI & GenAI Engineer (Azure & AWS)](https://www.scholarhat.com/job-oriented/multi-cloud-ai-genai-engineer-certification-training) \| [Multi-Cloud AI Architect (Azure & AWS)](https://www.scholarhat.com/job-oriented/multi-cloud-ai-architect-certification-training) #### Popular Live Training [.NET AI & ML Engineer Certification Training](https://www.scholarhat.com/training/net-ai-ml-certification-training) \| [.NET Certification Training](https://www.scholarhat.com/training/net-certification-training) \| [.NET Microservices Certification Training](https://www.scholarhat.com/training/net-microservices-certification-training) \| [.NET Software Architecture and Design Training](https://www.scholarhat.com/training/software-architecture-design-training) \| [Angular Certification Training](https://www.scholarhat.com/training/angular-certification-training) \| [ASP.NET Core Certification Training](https://www.scholarhat.com/training/aspnet-core-certification-training) \| [AWS AI & Gen AI Engineer Certification Training](https://www.scholarhat.com/training/aws-ai-engineer-certification-training) \| [AWS Developer Certification Training](https://www.scholarhat.com/training/aws-developer-associate-certification-training) \| [AWS Solutions Architect Certification Training](https://www.scholarhat.com/training/aws-solution-architect-certification-training) \| [Azure Agentic AI Engineer Certification Training](https://www.scholarhat.com/training/azure-agentic-ai-engineer-certification-training) \| [Azure AI & Gen AI Engineer Certification Training](https://www.scholarhat.com/training/azure-ai-engineer-certification-training) \| [Azure Developer Certification Training](https://www.scholarhat.com/training/microsoft-azure-developer-associate-certification-training) \| [Azure DevOps Certification Training](https://www.scholarhat.com/training/azure-devops-certification-training) \| [Azure Solution Architect Certification Training](https://www.scholarhat.com/training/microsoft-azure-solution-architect-certification) \| [Blazor Certification Training](https://www.scholarhat.com/training/blazor-certification-training) \| [Career Launchpad Program](https://www.scholarhat.com/training/career-interview-coaching-course) \| [Confidence, Communication & Leadership for Software Engineers](https://www.scholarhat.com/training/confidence-communication-leadership-software-engineers) \| [Data Structures and Algorithms Training](https://www.scholarhat.com/training/data-structures-algorithms-certification-training) \| [Java Microservices Certification Training](https://www.scholarhat.com/training/java-microservices-certification-training) \| [Python For Data Science and AI/ML Certification Training](https://www.scholarhat.com/training/python-data-science-ai-certification-training) \| [React Certification Training](https://www.scholarhat.com/training/reactjs-certification-training) \| [The Top 1% Tech Leader Program](https://www.scholarhat.com/training/tech-leadership-training-program) #### Platform - [Live Training](https://www.scholarhat.com/training) - [Free Courses](https://www.scholarhat.com/free-course) - [Hands-on Labs](https://www.scholarhat.com/labs) - [Real-World Projects](https://www.scholarhat.com/projects) - [DSA Problems](https://www.scholarhat.com/problems) - [Quick Notes](https://www.scholarhat.com/quicknotes) - [Free Interview Books](https://www.scholarhat.com/books) - [Corporate Training](https://www.scholarhat.com/corporate-training) #### Company - [About Us](https://www.scholarhat.com/about-us) - [Contact Us](https://www.scholarhat.com/contact-us) - [Terms & Conditions](https://www.scholarhat.com/terms-and-conditions) - [Privacy Policy](https://www.scholarhat.com/privacy-policy) - [Refund Policy](https://www.scholarhat.com/refund-policy) - [Subscription Policy](https://www.scholarhat.com/subscription-policy) - [Verify Certificate](https://www.scholarhat.com/certificate/verify) - [Become An Instructor](https://www.scholarhat.com/become-an-instructor) #### Resources - [Live Training Membership](https://www.scholarhat.com/membership/live) - [Master Classes](https://www.scholarhat.com/master-classes) - [Coding Playground](https://www.scholarhat.com/compiler) - [Skill Tests](https://www.scholarhat.com/skill-tests) - [Job Openings](https://www.scholarhat.com/jobs) - [Mentors](https://www.scholarhat.com/mentors) - [Live Batches](https://www.scholarhat.com/training/batches) - [Reviews](https://www.scholarhat.com/reviews) #### Have any Questions? ###### Course Enquires: - [\+91- 999 9123 502](tel:+919999123502) - [hello@scholarhat.com](mailto:hello@scholarhat.com) ###### Tech Support: - [\+91- 966 7279 501](tel:+919667279501) - [support@scholarhat.com](mailto:support@scholarhat.com) Follow Us © 2026 Dot Net Tricks Innovation Pvt. Ltd. \| All rights reserved \| The course names and logos are the trademarks of their respective owners \| Engineered with in India. We use cookies to make interactions with our websites and services easy and meaningful. Please read our [Privacy Policy](https://www.scholarhat.com/privacy-policy) for more details. [Accept Cookies]()
Readable Markdown
**Exception Handling in Python** is an essential concept that helps you manage and control runtime errors, known as exceptions, ensuring your program runs smoothly without unexpected crashes. Python provides the **try, except, else, and finally** blocks to handle exceptions effectively. Common exceptions include **ZeroDivisionError, TypeError, ValueError, and FileNotFoundError**. In this [Python tutorial](https://www.scholarhat.com/tutorial/python-exception-handling), we explore **how exception handling works in Python** with examples. Whether you're a beginner or an experienced developer, this guide will help you write error-free and robust Python programs. **Python developers earn up to 50% more than average coders. Don’t miss out Enroll in our** [Free Online Python Course](https://www.scholarhat.com/free-course/python-course-for-beginners) **today\!** ## What is Exception Handling? Exception handling is a technique in Python that deals with errors that occur during program execution.It entails spotting potential error situations, responding appropriately to exceptions when they arise, and identifying possible error conditions.Using the try and except keywords, Python provides a structured approach to exception handling. **By the end of this tutorial, you will gain a through understanding of:** - The concept of exceptions and why they occur in Python - The difference between syntax errors and exceptions - How to use try, except, else, and finally blocks for handling exceptions - Catching specific exceptions vs. using a generic exception handler - Raising exceptions manually using the raise keyword - Using the assert statement for debugging and error handling ![exception handling in python](https://dotnettrickscloud.blob.core.windows.net/article/python/5020250308183720.webp) ## Different Types of Exceptions in Python: Various built-in Python exceptions can be thrown when an error occurs during program execution. Here are some of the most popular types of Python exceptions: 1. **SyntaxError:** When the interpreter comes across a syntactic problem in the code, such as a misspelled word, a missing colon, or an unbalanced pair of parentheses, this exception is raised. Example: 2. **TypeError:** When an operation or function is done to an object of the incorrect type, such as by adding a [string](https://www.scholarhat.com/tutorial/python/strings-in-python) to an integer, an exception is thrown. 3. **NameError:** When a [variable](https://www.scholarhat.com/tutorial/python/variables-of-python) or function name cannot be found in the current scope, the exception NameError is thrown. 4. **IndexError:** This exception is thrown when a [list](https://www.scholarhat.com/tutorial/python/list-in-python), [tuple](https://www.scholarhat.com/tutorial/python/tuples-in-python), or other sequence type's index is outside of bounds. 5. **KeyError:** When a key cannot be found in a dictionary, this exception is thrown. 6. **ValueError:** This exception is thrown when an invalid argument or input is passed to a [function](https://www.scholarhat.com/tutorial/python/functions-in-the-python-language) or method. An example would be trying to convert a string to an integer when the string does not represent a valid integer. 7. **AttributeError:** When an attribute or method is not present on an object, such as when attempting to access a non-existent attribute of a class instance, the exception AttributeError is thrown. 8. **IOError:** This exception is thrown if an input/output error occurs during an I/O operation, such as reading or writing to a file. 9. **ZeroDivisionError:** This exception is thrown whenever a division by zero is attempted. 10. **ImportError:** This exception is thrown whenever a module cannot be loaded or found by an import statement. 11. **FileNotFoundError:**FileNotFoundError occurs when trying to open a file that does not exist. 12. **ModuleNotFoundError:**ModuleNotFoundError occurs when trying to import a module that is not installed or does not exist. 13. **BaseException:**The parent class for all built-in exceptions. 14. **Exception:**The superclass for all non-exit exceptions. ## Understanding try, except, else, and finally Blocks in Python ## 1\. try Block - This block contains the code that might cause an error. - If an error occurs, Python immediately jumps to the except block ### 2\. except Block - This block catches and handles the error if one occurs in the try block. - We can specify different types of exceptions or use a general one. ### 3\. else Block - Runs only if no exception occurs in the try block. - Useful when you want to execute some code only when there is no error. ### 4\. finally Block - Runs no matter what happens, whether there is an exception or not. - Useful for cleanup tasks (e.g., closing a file or database connection). ## Syntax of Exception Handling in Python ``` This is the basic syntax of a Try-Catch block in python. ``` ## Differences Between try and except in Python | | | | |---|---|---| | Feature | Errors | Exceptions | | Definition | Serious issues that stop the program from running | Issues that occur during execution but can be handled | | Causes | Syntax mistakes, missing modules, incorrect indentation | Incorrect input, division by zero, file not found, etc. | | Handling | Cannot be handled using **try-except** | Can be handled using try-except | | Examples | **SyntaxError, IndentationError, MemoryError** | **ZeroDivisionError, FileNotFoundError, KeyError** | Difference Between Exception and Error | | | | |---|---|---| | **Feature** | **Exception** | **Error** | | **Definition** | An exception is an event that occurs during program execution and disrupts the normal flow of instructions. | An error is a serious issue in the program that prevents it from continuing execution. | | **Recoverability** | Can be handled using try-except blocks. | Generally, errors are unrecoverable and should be fixed in the code. | | **Causes** | Caused by logical mistakes, invalid user input, or unforeseen conditions. | Caused by system failures, memory overflow, or hardware limitations. | | **Examples** | **ZeroDivisionError, IndexError, KeyError, FileNotFoundError** | **MemoryError, StackOverflowError, OutOfMemoryError, SystemError** | | **Handling** | Can be caught and handled by the program. | It cannot be caught easily and usually requires fixing the underlying issue. | Try and Except Statement – Catching Exceptions - In Python, you may catch and deal with exceptions by using the try and except commands. - The try and except clauses are used to contain statements that can raise exceptions and statements that handle such exceptions. - Exception handling in Python helps to manage errors in a program. - With exception handling in Python, you can prevent your code from crashing. ## Example of Try and Except Statement in Python ``` ``` In this example in the [**Python Editor**](https://www.scholarhat.com/compiler/python), the try block attempts to divide 10 by the input entered by the user. The result is calculated and reported if the input is a valid integer that is not zero. If the input is invalid (for example, [a string](https://www.scholarhat.com/tutorial/python/strings-in-python)) or zero, the corresponding except block raises an exception and displays an appropriate error message. #### Output ``` Enter a number: 0 Division by zero is not allowed. ``` ## Catching Specific Exception - To provide handlers for various exceptions, a try statement may contain more than one except clause. - Please be aware that only one handler will be run at a time. - Exception handling in Python uses try and except blocks to catch errors. - Debugging becomes easier with exception handling in Python. ## Example of Catching Specific Exception in Python ``` ``` This code will attempt to open the file "test.txt" and read its contents. The code will print an error message if the file is not found. If an error occurs while reading the file, the code will display an error message before proceeding to the next line of code. #### Output ``` File not found. ``` Try with Else Clause - Python additionally allows the use of an else clause on a try-except block, which must come after every except clause. - Only when the try clause fails to throw an exception does the code go on to the [else block](https://www.scholarhat.com/tutorial/python/decision-making-statements-if-else-nested-if-else). - Using exception handling in Python, you can write safer and more reliable programs. Example of Try with Else Clause in Python ``` ``` A try block is used in this example to read "test.txt" and look for the word "Python." If the file access is successful, the otherwise block is executed. If an exception occurs, such as FileNotFoundError, the error is handled by the associated except block. #### Output ``` The file 'test.txt' could not be found. ``` ## Finally Keyword in Python - The final[keyword in Python](https://www.scholarhat.com/tutorial/python/keywords-in-python)is always used after the try and except blocks. - The try block normally terminates once the final block executes, or after the try block quits because of an exception. ## Example of Finally Keyword in Python ``` ``` The code defines the [function](https://www.scholarhat.com/tutorial/python/functions-in-the-python-language) divide\_numbers, which attempts to divide two numbers, prints the result if successful, handles the division by zero exception, and ensures that a final block of code (finally) always executes, regardless of whether an exception occurred or not. #### Output ``` The result of 10 divided by 2 is: 5.0 This block always executes, regardless of exceptions. Error: Cannot divide by zero! This block always executes, regardless of exceptions. ``` ## Catch-All Handlers and Their Risks - **Unintended Exception Handling:**Catching all exceptions (except Exception:) may suppress critical errors, making debugging difficult. - **Hidden Bugs:**Swallowing exceptions without proper logging can obscure the root cause of issues. ### Example of Catch-All Handlers and Their Risks in Python ``` ``` #### Output ``` An error occurred: An unexpected error occurred. ``` ## Catching Multiple Exceptions - **Handling Specific Errors**: Catching multiple exceptions allows handling different error types separately. - **Better Debugging:**Helps identify the exact cause of failure rather than using a generic catch-all handler. ### Example of Catching Multiple Exceptions in Python ``` def safe_divide(a, b): if b == 0: raise ZeroDivisionError("Cannot divide by zero.") return a / b try: num1, num2 = map(int, input("Enter two numbers: ").split()) result = safe_divide(num1, num2) print("The result is:", result) except ZeroDivisionError as e: print("Error:", e) except ValueError as e: print("Invalid input. Please enter numbers only.") ``` #### Output ``` Enter two numbers: 10 0 Error: Cannot divide by zero. ``` ## Raise an Exception - The raise statement enables the programmer to compel the occurrence of a particular exception. - Raise's lone argument specifies the exception that should be raised. - Either an exception instance or an exception class (a class deriving from Exception) must be present here. ## Example of Raising Exception in Python ``` ``` The code in the [**Python Compiler**](https://www.scholarhat.com/compiler/python) implements a divide [function](https://www.scholarhat.com/tutorial/python/functions-in-the-python-language) to conduct division, throwing a ZeroDivisionError if the divisor is 0. It then attempts to call this method, prints the result if successful, and throws an exception if division by zero happens. #### Output ``` The result is: 5.0 ``` ## New Features in Exception Handling in Python 3.10 and 3.11 | | | | |---|---|---| | Feature | Python 3.10 | Python 3.11 | | Clearer Error Messages | Error messages became easier to understand. | Error messages are now even more helpful — they point to the exact part of the code that caused the issue. `SyntaxError: '(' was never closed` Shows arrows like `--> divide(x, y)` so you know exactly where it broke. | | Pattern Matching for Errors | You can match errors using `match-case`, like matching puzzle pieces. `match err: case FileNotFoundError(): print("File error")` | Same in 3.11 — just as useful. | | Handle Many Errors Together | Not possible. | New in 3.11! You can catch multiple errors at once using `except*`. `except* ValueError: print("Handled group")` | | Faster Exception Handling | No speed improvements. | Running try-except blocks is now around 10–15% faster. | ### Python 3.10 - **Better Error Messages**: Syntax errors now provide clearer and more specific messages, making debugging easier. - **Pattern Matching for Exceptions**: A new way to handle exceptions using structural pattern matching, making code more readable and organized. ### Python 3.11 - **Faster Exception Handling:** Performance improvements make exception handling up to 10-15% faster. - **More Detailed Tracebacks :**Tracebacks now highlight the exact line and expression where the error occurred, improving debugging. - **Exception Groups:**Allows multiple exceptions to be raised and handled together, useful for concurrent and batch processing. Advantages of Exception Handling - **Increased program dependability:** By managing exceptions correctly, you can stop your program from crashing or generating wrong results because of unforeseen faults or input. - **Error handling made easier:** It is simpler to comprehend and maintain your code when you can separate the error management code from the core program logic using exception handling. - **Simpler coding:** With exception handling, you can write code that is clearer and easier to comprehend by avoiding the use of intricate conditional expressions to check for mistakes. - **Simpler debugging:** When an exception is raised, the [Python interpreter](https://www.scholarhat.com/tutorial/python/interpreter-in-python) generates a traceback that identifies the precise place in your code where the error happened. ## Disadvantages of Exception Handling - **Performance penalty:** Because the interpreter must undertake an extra effort to detect and handle the exception, exception handling can be slower than utilizing conditional statements to check for mistakes. - **Code complexity increase:** Handling exceptions can make your code more difficult, especially if you have to deal with a variety of exception types or use sophisticated error-handling logic. - **Possible security risks:** It's critical to manage exceptions carefully and avoid disclosing too much information about your program because improperly handled exceptions may reveal sensitive information or lead to security flaws in your code. #### Summary In this article, we have understood that Exception handling is and important concept in Python. It ensures that any mistake or unforeseen input does not cause the program to crash. Exception handling can be used to check both syntax levels and validations accordingly. **Only 5% of Python coders become full-stack experts. Be one of them with our [Full-Stack Python Developer Certification Training](https://www.scholarhat.com/job-oriented/full-stack-python-developer-certification-training). Enroll today to lead, not follow\!** #### Q 1: What is the purpose of the try-except block in Python? - To handle exceptions - To define functions - To iterate over lists - To declare variables ### FAQs The "ZeroDivisionError" that occurs when dividing by zero is an illustration of an exception in Python. User-defined exceptions and built-in exceptions, such as ValueError and IndexError, are the two basic categories of exceptions in Python. Python's "try" and "except" blocks are used to handle exceptions. An exception explicitly relates to runtime defects that may be caught and handled in Python, whereas an error is a broader phrase that refers to mistakes in code. ## Take our Python skill challenge to evaluate yourself\! ![]() In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill. [GET FREE CHALLENGE](https://www.scholarhat.com/skill-test/python?utm_source=Scholarhat&utm_medium=Article&utm_campaign=Get_Free_Challange&utm_term=https://www.scholarhat.com/tutorial/python/exception-handling-in-python)
Shard76 (laksa)
Root Hash5572162201820126676
Unparsed URLcom,scholarhat!www,/tutorial/python/exception-handling-in-python s443