Exception Handling in Python – A Complete Guide

Updated on July 24, 2024

Article Outline

Exception handling is resolving the runtime errors that occur in a program. These errors are mainly caused by invalid user input or invalid code in Python. Exception Handling allows the program to continue to execute even if an error occurs. In this article, we will learn everything about exception handling in the Python programming language.

What is Exception Handling?

In the Python language, an exception is an event that disrupts the normal flow of program execution. When an error occurs in a Python script, the interpreter halts the current process and passes the exception to a special handler that can resolve the issue. If the handler is not found, the program will terminate.

 

Exception handling in Python is achieved using the try and except blocks. The try block is used to enclose code that may raise an exception. This block will handle the exception if it occurs in the Python script.

 

The basic syntax of a try-except block in Python is as follows.

 

Syntax

try: # code that may raise an exception except: # code to handle the exception

Note: Python Developers must remember that the try and except blocks must be used together to handle exceptions properly. Writing just the try or except block alone will result in an error.

*Image
Get curriculum highlights, career paths, industry insights and accelerate your technology journey.
Download brochure

Common Exceptions in Python

Before learning more about exception handling in Python, we need to understand some of the common exceptions that Python throws.

 

In Python language, All the inbuilt exceptions in Python are inherited from the common “Exception class”. The common inbuilt exceptions are:

 

Exception Name Description
Exception This class in Python inherit all the base classes of all exception
StopIteration  The next() method of an iterator while iterations does not point to any object in Python
StandardError All the exceptions inherit this class except stop StopIteration and SystemExit
Arithmetic Error The errors that occur during numeric calculations are inherited by it.
OverflowError When a calculation exceeds the max limit for a specific numeric data type
ZeroDivisonError Raised when division or modulo by zero takes place.
AssertionError Raised when an assert statement fails.
AttributeError Raised in case of failure of attribute assignment
ImportError The raised when an import statement fails
EOFError The raised when the end of the file is reached usually occurs when there is no input from the input() function
 NameError This is raised when an identifier is not found in the local, non-local or global scope.
Syntax Error This exception occurs when the error occurs in the Python syntax
IdentationError This error occurs when indentation is not proper
TypeErrror This rises when a specific function operation is triggered by an invalid data type.
ValueError Raised when invalid values are provided to the arguments of some builtIN function for the data type with a valid type of arguments.
RuntimeError They are raised when an error does not fall into any other category.
NotImplementedError The issue is raised when an abstract method that needs to be implemented in an inherited class is not implemented.

 

These exceptions are very common in the Python language. More exceptions are available in Python’s official documentation on exceptions.

Catching Specific Exceptions in Python

In this section, we will catch the exception that occurs in a Python program. This is being raised in the try and block catch exceptions that try might raise. Python developers have to consider catching specific types of exceptions and handling them accordingly. They can implement multiple except blocks. We can also use a tuple of values in an except to receive multiple specific exception types.

 

The following program demonstrates how to catch specific exceptions in Python.

 

Program

def divideNumber(a, b): return a/b try: a = int(input('Enter Number first  a:')) b = int(input('Enter Number Second b: ')) print(divideNumber(a,b)) c = [1, 2, 3] print(c[3]) except IndexError: print('index error') except ZeroDivisionError: print('zero division error')

Output

Enter Number first  a:2 Enter Number Second b: 0 zero division error
  • In the above example, the exception raised depends upon the input that user input the user might enter. If the user enters a value as 0 for ‘b’, the Python interpreter will raise a ZeroDivisionError exception.
  • We also set the c variable to a length of 3. When the user tries to access an element at index 3, the Python interpreter will raise an IndexError.
  • The except block has been defined for both exceptions, as one of them received exceptions of type IndexError and the other received exceptions of type ZeroDivisonError.

Raising Custom Exceptions

In Python, we can also define custom exceptions that are automatically raised in the runtime when an error occurs. Custom and predefined exceptions can be thrown manually by raising the specific condition met in the Python program. A custom exception is an exception that Python developers raise if they need to break the flow of code in a specific scenario or condition.

Syntax to Raise an Exception

try: # on some specific condition or otherwise raise SomeError(OptionalMsg) Except SomeError as e: # Executed if we get an error in the try block # Handle exception ‘e’ accordingly

The following program demonstrates the Custom Exception.

 

Program

def isStringEmpty(text): if(type(text)!=str): raise TypeError('str has to be string') if(not text): raise ValueError('str cannot be null') text.strip() if(text == ''): return False return True   try: text = 4343 print('isStringEmpty:', isStringEmpty(text)) except ValueError as e: print('ValueError raised:', e)   except TypeError as e: print('TypeError raised:', e)

Output

TypeError raised: str has to be a string
  • In the above code, the variable ‘text’ can hold whatever value is assigned to it. Here, we will assign it a number and pass it to a custom method, isStringEmpty, that checks if a string is an empty string.
  • It will throw TypeError, by passing the ‘text’ variable a number.
  • In this method, we check whether the variable is a string and whether it holds a value. In this case, the text variable is supposed to be a string type. But we assigned it a number as we’re raising an exception by using it.

try-except and ELSE

 

Sometimes, developers want to run specific code only with no exceptions. For such scenarios, the Python language has an else keyword that can be used with a try block. The developer has to remember that the else keyword is optional.

 

Syntax with Else Clause

try: # on some specific condition or otherwise raise SomeError(OptionalMsg) except SomeError as e: # Executed if we get an error in the try block # Handle exception ‘e’ accordingly else # Executed if no exceptions are raised

The following program demonstrates the try-except and else examples.

 

Program

try: b  = 10 c = 2 a = b/c print(a) except: print('Exception raised') else: print('no exceptions raised')

Output

5.0 no exceptions raised

In the above example, both inputs are greater than zero, which does not take to DivideByZeroException. This means the try block will not raise any exception, so the except block will never be triggered. Then, it will run the else block of the code. The handling can be done inside this else block if the developer wants to do something.

Try Clause with Finally

Python developers can also use the finally keyword with try and block. The finally block is a place to put any code that must be executed, whether the try and block raised an exception or not.

 

The Syntax of the try-finally statement:

 

Syntax

try: # Code that might cause an exception result = 10 / 2 print("Result:", result) finally: # Code that will always be executed print("This will run no matter what.")

The following program demonstrates the try clause with finally keyword.

 

Program

try: # Code that causes an exception result = 10 / 0 except ZeroDivisionError: print("Cannot divide by zero!") finally: # Code that will always be executed print("This will run no matter what.")

Output

Cannot divide by zero! This will run no matter what.

Advantages of Exception Handling

There are many advantages of Exception Handling. Here, we are describing some of the most common advantages.

 

  • Improve Program Stability: Exception handling allows programs to run smoothly even when unexpected errors occur. Catching and handling exceptions can prevent the entire program from crashing due to unexpected or unhandled errors while our programming is running.

 

  • Separations of Error-Handling Code: Exception handling separates the error-handling code from the program’s regular logic. Exception handling makes the program cleaner and easier to read, helping the developer maintain and debug the code more efficiently.

 

  • Flexibility: Python language allows defining custom exceptions, providing the flexibility to create meaningful and specific error messages that can convey detailed information about the problem.

Disadvantages of Exception Handling

Here, we are describing the disadvantages of exception handling:

 

  • Performance Overhead: Handling the exception can introduce some performance overhead. The raising and catching exceptions are generally slower than regular control flow constructs. Exception handling can be significant in performance-critical applications.

 

  • Misuse of Exceptions: Overusing or incorrectly using exceptions can lead to a code that is hard for the developer to understand and maintain.
  • Complexity: Exception handling can add complexity to the code, especially when dealing with multiple types of exceptions and nested try-except blocks. It can make the code difficult for the developer to follow and maintain.

 

  • Debugging Difficulty: If the exception is caught and handled inappropriately, it can aid in debugging by providing tracebacks. However, if not used properly, it can also make debugging difficult.

Conclusion

In this article, we learned that exception handling is a powerful feature in Python that enhances program stability, readability, and maintainability. However, It should be used judiciously to avoid performance overhead, complexity and the risk of masking underlying issues. By effectively using exception handling  ‘try’, ‘except’ , ‘else’ and ‘finally’ blocks, you can manage errors gracefully and ensure your code can handle unexpected situations without crashing the application. By understanding exception handling, developers can follow best practices, such as catching specific exceptions and avoiding silent features. You can leverage exception handling to create a more resilient and reliable Python application.

 

FAQs
An exception in Python is an event that disrupts the normal flow of program execution. It typically occurs due to errors like division by zero, accessing a non-existent file, or using an invalid index in a list.
In Python, we can handle exceptions using the ‘try’ and ‘except’ blocks. The code that might cause an exception is placed inside the ‘try’ block, and the code to handle the exception is placed inside the ‘except’ block.
Yes, Python exception handling can introduce some performance overhead. Raising and catching exceptions are generally slower than using regular control flow constructs.

Updated on July 24, 2024

Link
left dot patternright dot pattern

Programs tailored for your success

Popular

Management

Data Science

Finance

Technology

Future Tech

Upskill with expert articles

View all
Hero Vired logo
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.
Blogs
Reviews
Events
In the News
About Us
Contact us
Learning Hub
18003093939     ·     hello@herovired.com     ·    Whatsapp
Privacy policy and Terms of use

|

Sitemap

© 2024 Hero Vired. All rights reserved