Sitemap
LearnPython

From beginners to experts, find code snippets, practical examples, and step-by-step guides to master Python programming

Member-only story

Exception Handling in Python

--

Press enter or click to view image in full size
Photo by Mohammad Rahmani on Unsplash

Errors and exceptions can lead to unexpected behaviour or even stop a program from executing. Python provides various functions and mechanisms to handle these issues.

An error is an issue in a program that prevents the program from completing its task. In comparison, an exception is a condition that interrupts the normal flow of the program. Both errors and exceptions are a type of runtime error, which means they occur during the execution of a program.

Python Exceptions

An exception is an unexpected event that occurs during program execution. The Errors that occur at runtime (after passing the syntax test) are called exceptions or logical errors.

For instance, they occur when we

  • try to open a file(for reading) that does not exist (FileNotFoundError)
  • try to divide a number by zero (ZeroDivisionError)
  • try to import a module that does not exist (ImportError) and so on.

Whenever these types of runtime errors occur, Python creates an exception object.

If not handled properly, it prints a traceback to that error along with some details about why that error occurred.

📌 Example :



divide_numbers = 7 / 0
print(divide_numbers)



# Error…

--

--

Shaloo Mathew
Shaloo Mathew

Written by Shaloo Mathew

I love working with data and finding the stories it tells. Through analytics and technology, I aim to turn data into useful insights.

LearnPython
LearnPython

Published in LearnPython

From beginners to experts, find code snippets, practical examples, and step-by-step guides to master Python programming