Sitemap

Exception in python

3 min readMay 26, 2024

--

In this lecture, we will learn how to handle errors in Python. In Python, there are two main types of errors:

  1. Syntax errors: These occur when there’s a mistake in the code’s structure.
  2. Exceptions: These occur when the code runs into a problem during execution.

Let’s take an example to understand syntax errors:

Press enter or click to view image in full size

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:

Press enter or click to view image in full size

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:

Press enter or click to view image in full size

For each try block, there can be zero or more except blocks. Multiple except blocks allow us to handle different exceptions separately

Press enter or click to view image in full size

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

Press enter or click to view image in full size

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.

Press enter or click to view image in full size

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.

Press enter or click to view image in full size

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:

Press enter or click to view image in full size

--

--

Rakesh Sharma
Rakesh Sharma

Written by Rakesh Sharma

Data engineer with 11 years IT experience, specializing in ML, DL, data modeling, RDBMS, Hadoop, Spark, Scala, PySpark, Hive, Sqoop, Linux.