Python exception Handling | Error Handling

Python exception Handling or Error Handling is a prevent to your application (program) to crash. An Exception is a programmatic error that happens during the execution of a program. So in a python, some error is most common and know, when that error occurs that time your program should handle those errors called an exception Handling or Error Handling.

So your program (application) should be developed (coded) like which handles the exception. In this tutorial, you will learn about Python exception Handling in detail with examples.

Python exception Handling | Error Handling print Raising types

Exceptions

Errors detected during execution or Python runtime error are called exceptions and are not unconditionally fatal.

Some Python Exception Types 

Here is some common exception in python

  • except IOError: It occurs when Input Output operation fails.
  • except ValueError: Non-numeric data found in the file.
  • except ImportError: NO module found
  • except IndentationError: If incorrect indentation is given.
  • except: Any error occurred

Official link of a list of built-in exceptions with their meanings – Built-in Exceptions, this is built-in python exception class.

Handling Exceptions

You can Handle the exception using an try except block.

Simple syntax of try except block for exception handling in python.

Python exception Handling Example 

It’s a simple example to Handle an exception in the program. Where in Programme diving the 7 by 0, which is logically wrong. So their program should throw an error.

Output: Exception Occurred

Print exception

Print a python exception message (system default message) to understand what kind of error is there. The upper example is handling a board exception, which is not preferable. You have to specify what kind of exception can it be.

Here is an example of how to Python print exception.

Output:  division by zero

Raising Exceptions

With the raise statement, you can specify an exception to occur in the program. Its called a raise exception in python. Let’s see the example of raise Exception Handling.

Output:

example of raise exception Handling output

QA: How to Declare Multiple Exception in Python?

Using more except to get multiple checkpoints in the program.

Or like this example

Output: Arithmetic Error

Note: In this tutorial, we are not adding finally and else examples, You must read this tutorial “Python try except | Finally | Else | Print Error Examples” to complete code practice.

Do comment if you have any doubt and suggestion on this tutorial.

Note: This example (Project) is developed in PyCharm 2018.2 (Community Edition)
JRE: 1.8.0
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.13.6

Python 3.7

All examples are of Exception Handling in python 3, so it may change its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.