Exception in python
In this lecture, we will learn how to handle errors in Python. In Python, there are two main types of errors:
- Syntax errors: These occur when there’s a mistake in the code’s structure.
- Exceptions: These occur when the code runs into a problem during execution.
Let’s take an example to understand syntax errors:
This will throw an error because there’s a typo in the print function. Once we correct it and run the program again, it will work correctly and give us the desired output. This type of error is called a syntax error, and it occurs during the compilation of the program.
Now, let’s look at an example of an exception:
This error occurs because the logic in the program is incorrect (you can’t divide by zero). This error won’t be detected during compilation but will occur when the program runs.
To handle exceptions, Python provides try and except blocks. In the try block, we write the code that might cause an exception, and in the except block, we write the code to handle the exception. The try block will always execute, and the except block will execute only if an exception occurs.
Get Rakesh Sharma’s stories in your inbox
Join Medium for free to get updates from this writer.
Let’s fix the previous example:
For each try block, there can be zero or more except blocks. Multiple except blocks allow us to handle different exceptions separately
We can also use an else block with try and except. The else block is executed only if no exception occurs in the try block. This is useful for code that should run only if everything executes successfully
If we want to run some code even if an exception occurs, we can use the finally block. The finally block is always executed, no matter whether there is an exception or not. The finally block is optional, and for each try block, there can be only one finally block.
In Python, the raise keyword is used to manually trigger an exception. This can be useful when you want to enforce certain conditions in your code and throw an error if those conditions are not met.
Python has many built-in exceptions that are raised when specific errors occur. We can see all the built-in exceptions using the locals() function. Let’s take an example to understand this:









