Python Exception Handling with Examples

In this article we are going to cover Python Exception Handling with Examples, List of Exception errors in Python, Example of raise the exception with message in Python.

The try blocks lets you test a block of code for errors.

The except block lets you handle the error.

The finally block lets you execute code, regardless of the result of the try- and except blocks.

Exception = Error

Exception are abnormal termination of program this occurred abruptly during runtime and stop the exception of the program.

There are two types of exception:-

  1. System- defined exception.
  2. User – defined exception.

Python Exception Handling: 

It is an abnormal event which occurs at the runtime and suspends the execution.

Python having the capability for managing the execution.

Exception can be handled in python using try except keyword.

Errors are of two types

  1. Compile errors
  2. Logical errors

List of Exception errors in Python:

  • IOError : If file can’t opened.
  • KeyboardInterrupt : When an unrequired key is pressed by the user.
  • ValueError : When built-in function receives a wrong argument.
  • EOFError : If End-Of-File is hit without reading any data.
  • ImportError : If it is unable to find the module.

The critical operation which can raise an exception is placed inside the try clause. The code that handles the exception is written in the except clause.

Syntax:

try:
	//statements
except:
	//statements

Example of exceptions can be handled using the try statement in Python:

try:
  print(a)
except:
  print("An exception occurred")

Output:

An exception occurred

The try block will generate an exception, because a is not defined:

Python Exception Handling with Examples 1

No Exception, so try clause will run

Example :

def add(a, b): 
	try: 
		
		result = a + b 
		print("Your answer is :", result) 
	except ZeroDivisionError: 
		print("Sorry ! You have an Error ") 


add(3, 2)

Output:

Your answer is : 5
Python Exception Handling with Examples 2

There is an exception so except clause will run.

Example:

def divide(a, b): 
	try: 
		 
		result = a / b 
		print("Yeah ! Your answer is :", result) 
	except ZeroDivisionError: 
		print("Sorry ! You are dividing by zero ") 


divide(3, 0)

Output:

Sorry ! You are dividing by zero
Python Exception Handling with Examples 3

The try block does not generate any error so else block is executed

Example:

try:
  print("Hello world")
except:
  print("Something went wrong")
else:
  print("Nothing went wrong")

Output:

Hello world
Nothing went wrong
Python Exception Handling with Examples 4

Finally

The finally block gets executed no matter if the try block raises any errors:

Example of finally block in Python:

try:
  print(a)
except:
  print("Something went wrong")
finally:
  print("The 'try block and except block' is finished")

Output:

Python Exception Handling with Examples 5

Example of Raising Exception for predefined condition:

try: 
	age = 17
	if age <= 18: 
		raise ValueError("You are not Eligible") 
	else: 
		print("You are Eligible") 
except ValueError as e: 
		print(e)

Output:

You are not Eligible
Python Exception Handling with Examples 6

Example of raise the exception with message in Python:

try:  
     num = int(input("Enter a positive integer: "))  
     if(num <= 0):  
         raise ValueError("That is  a negative number!")  
except ValueError as e:  
     print(e)  

Output:

Enter a positive integer: -9
That is  a negative number!
Python Exception Handling with Examples 7

Another Example:

try:    
    a = int(input("Enter a:"))    
    b = int(input("Enter b:"))    
    if b is 0:    
        raise ArithmeticError  
    else:    
        print("a/b = ",a/b)    
except ArithmeticError:    
    print("The value of b can't be 0")  

Output:

=========
Enter a:10
Enter b:10
a/b =  1.0
or
Enter a:10
Enter b:0
The value of b can't be 0
Python Exception Handling with Examples 8

Conclusion:

We have covered Python Exception Handling with Examples.

Related Articles:

Functions in Python with Examples

Loops in Python 3 with Examples

7 Python Operators with Examples

Python Introduction for Programmers [Part 1]

6 Python Conditional Statements with Examples

Inheritance in python with examples

Encapsulation and Polymorphism in Python with Examples

Python RegEx with Examples

Python Datetime with Examples

File Handling in Python with Examples

Reference:

Python Exception Handling official page

FOSS TechNix

FOSS TechNix (Free,Open Source Software's and Technology Nix*) founded in 2019 is a community platform where you can find How-to Guides, articles for DevOps Tools,Linux and Databases.

Leave a Comment

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

Share via
Copy link