- Python Roadmap
Table of contents
- What is Exception Handling?
- Types of Exceptions
- How to handle Exceptions ?
- Raising an Exception in Python
- How to write Custom Exceptions ?
- Finally Block
- Multiple Exceptions
- Try-Except-Else Statement
- How does Exceptions Propagate ?
- Assertions in Python
Python is a modern, high-level programming language that is widely used by developers around the world. One of the most important aspects of any Programming language is exception handling. Exceptions are errors that occur during the execution of your program, and they can be caused by a variety of factors, such as incorrect user input or system errors or other errors such as syntax, invalid operations etc.
What is Exception Handling?
Exception handling is the process of dealing with exceptions that occur during the execution of a program. In Python, exceptions are managed using the try-except block. The try block contains the code that may raise an exception, while the except block contains the code that handles the exception.
Using try-except block in your Python programs allow you to handle cases that may cause your program to behave unexpectedly.
Types of Exceptions
There are several types of exceptions in Python, some of the most common exceptions are :
- SyntaxError: Occurs when there is a syntax error in the code.
- TypeError: Occurs when an operation or function is applied to an object of inappropriate type.
- NameError: Occurs when a variable is referenced before it has been assigned a value.
- FileNotFoundError: Occurs when a file cannot be found.
- ValueError: Occurs when a function argument has the correct type, but an inappropriate value.
How to handle Exceptions ?
As we mentioned above, to handle an exception, we use the try-except blocks. Here's an example:
try: # code that might raise an exception except: # code that will handle the exception
In this example, the try block contains the code that may raise an exception, while the except block contains the code that handles the exception.
If you want to handle certain exceptions differently, we can also specify the type of exception that we want to handle. For example:
try: # code that might raise an exception except ValueError: # code to handle the ValueError exception except: # code that will handle the exception
In this example, the first except block handles the
ValueError exception, while the second except block handles any other exception. This type of exception handling is very useful in cases where you want to do certain operations only on
ValueError but not on any other exceptions.
Raising an Exception in Python
There are times when you want to raise exceptions manually. This can easily be done by manually raising exceptions using the raise keyword. For example:
if x < 0: raise ValueError("x cannot be negative")
In this example, we are first checking if value of
x is less than 0, if yes then we raise a ValueError exception.
How to write Custom Exceptions ?
In Python, creating custom exceptions is very simple. Let's raise an exception with a simple string message in it:
if not x: raise Exception("x cannot be None")
We can also create our own custom exceptions by defining a new class that inherits from the built-in
Exception class. Here's an example:
class MyException(Exception): pass
In this example, we define a new exception class called
MyException that inherits from the built-in
Exception class. We can then raise this exception using the raise keyword:
if x < 0: raise MyException("x cannot be negative")
In addition to the try and except blocks, Python also provides a finally block. The code in the finally block is executed regardless of whether an exception was raised or not. Here's an example:
try: # code that might raise an exception except: # code that will handle the exception finally: # code that is always executed
In this example, the code in the finally block is always executed, regardless of whether an exception was raised or not.
So far we saw how to raise and handle single exceptions. We can also handle multiple exceptions in a single try block. Here's an example:
try: # code that might raise an exception except (ValueError, TypeError): # code to handle either a ValueError or a TypeError exception except: # code that will handle the exception
In this example, the first except block handles either a ValueError or a TypeError exception, while the second except block handles any other exception.
Python also provides a try-except-else statement, which allows us to run some code if no exception is raised. Here's an example:
try: # code that might raise an exception except (ValueError, TypeError): # code to handle the ValueError exception except: # code that will handle the exception else: # code that is executed if no exception is raised
In this example, the code in the else block is executed if no exception is raised. This can be useful for cases where we want to perform some action only if the code in the try block succeeds and not always like it does with
How does Exceptions Propagate ?
In Python, exceptions can be propagated from a function to its caller. This is called Exception Propagation. When an exception is raised in a function, the function terminates immediately and the exception is passed to the caller. If the caller does not handle the exception, it is propagated to the next level of the call stack, and it goes on. At the end of this, either the exception will break the flow of program or will be handled by Exception handling.
Here's an example:
def function1(): function2() def function2(): function3() def function3(): raise ValueError("Error in function3") try: function1() except ValueError: print("Caught ValueError")
In this example, the
function3 raises a
ValueError exception, which is propagated to the caller,
function2, and then to the caller,
function1. Finally, the exception is caught by the try block in the main program, and the message "Caught ValueError" is printed.
Assertions in Python
Another important topic in Exception handling with Python is Assertions. This is often neglected by people.
Assertions are another way to handle errors in Python. An assertion is a statement that checks if a condition is true, and if it's not, it raises an
AssertionError. Let's understand this with an example:
x = 5 assert x == 5, "x should be 5"
In this example, we use the assert statement to check if the value of
x is equal to
5. If it's not, the assert statement raises an
AssertionError with the message "x should be 5".
Assertions can be useful for checking that our code is working as expected, and for catching errors early in development.
Other than that, Assertions are also actively used while writing test cases for your python code.
Phew! That was a long post, right ? In this blog post, we learned about how Exception handling and assertions are important aspects of Python programming. By understanding how to handle exceptions and use assertions, we can write more robust and reliable code.
Thanks for reading! If you have any questions, feel free to discuss with us on the comments.