Introduction

Setup

Operators

variable

String

Number

Dtype & Comment

Lists

Tuples

Sets

Dictionaries

if else statement

For Loop

While Loop

iterator & iterable

Pre-Built functions

Function

Decorators

Generators

Types of errors

Exceptions Handling

OOP

Regular expression

Create module

OS module

Date module

Random module

Math

Statistics module

Exercise 1

Exercise 2

Exercise 3

Learn Data Structure & Algorithm

Learn Numpy

Learn Pandas

Learn Matplotlib

Learn Seaborn

Learn Statistics

Learn Math

Learn MATLAB

Learn Machine learning

Learn Github

Learn OpenCV

Learn Deep Learning

Learn MySQL

Learn MongoDB

Learn Web scraping

Learn Excel

Learn Power BI

Learn Tableau

Learn Docker

Learn Hadoop

Python exception handling

Python exception

Exceptions are those errors that occur while coding execution. Suppose we have to give input in number format but we gave in string format. This will raise an error while code execution and it is called an exception.

Example:Suppose we wrote for loop. We know that after the for loop declaration line when we wrote the second line then we have to give space before writing the second line. If somehow we forget to give this space then we will get an indentation error.

Example:Suppose we want to print a variable or a list or a tuple but we didn't define the variable or list or the tuple. So in this case we will get a name error.

Example:Suppose you have a tuple which contain total 4 elements. Now you want to get the last element. So you write index number 4. But the indexing starts from 1 and the last element index will be 3 but you passed 4. So you will an index error.

How to handle exception in python?

To handle exceptions we use to try, except, else and finally keyword. Before using these keywords we should know that in which part of the code we can get an error.

Example:
Suppose you wrote a program. Now in the program user have to give a input and according to the input the program will run and the user will get his or her desire output. Now there is a problem and the problem is, user must put or pass integer value. If he or she doesn't put integer value then the program will not run. So you have to show a custom error in the program so that the user can understand that where he did mistake and how solve the problem to run the program. Now look here one thing, here you know that where error can occur. If you don't that where an error can occur. Only then you can raise an error. Because if you don't know that where the error can occur then how do you will know that what types of error you have to raise and when. So you must know that where an error can occur and as solution of the error you have to raise an error.

Example:1
Input
try:
  age=int(input("Enter your age:"))
except ValueError:
  print("You have passed wrong input. Please type correct input ")
if age< 18:
  print("You can't play this game because you are under age")
else:
  print("You can play this game. You are perfect candidate for this game. Have fun")
Output
Enter your age:seven
You have passed wrong input

At first, we have to find in which line we can get an error and what type of error. In example 1 we can get an error in the first line and the error can be a value error.
So we wrote try: and put that line inside try. Then we write except and in front except we have to write the error name which we can get. Then we can print a message there.

Example:2
Input
try:
  age=int(input("Enter your age:"))
except ValueError:
  print("You have passed wrong input ")
except:
  print("Unknown error ")
if age< 18:
  print("You can't play this game")
else:
  print("You can play this game")
Output
Enter your age:rfr
You have passed wrong input

Suppose we thought we will get a value error. But somehow we got another type of error. Now, what we should do?
To solve this problem we can use another except and in front of this except we will not write the name of the error. After this, we can print a massage.

Example:3
Input
while True:
  try:
    age=int(input("Enter your age:"))
    break
  except ValueError:
    print("You have passed wrong input ")
  except:
    print("Unknown error ")
if age< 19:
  print("You can't play this game")
else:
  print("You can play this game")
Output
Enter your age:
You have passed wrong input
Enter your age:45
You can play this game

We can also run a while loop until the user passes the correct input. It can be a good solution.

Example:4
Input
while True:
  try:
    age=int(input("Enter your age:"))
    break
  except ValueError:
    print("You have passed wrong input ")
  except:
    print("Unknown error ")
  else:
    Print("User input {age}")
    break
  finally:
    print("Work is done.......")
if age< 19:
  print("You can't play this game")
else:
  print("You can play this game")
Output
Enter your age:fgfg
You have passed wrong input
Work is done.......
Enter your age:19
Work is done.......
You can play this game

In example 4 what we wrote in else block we can also write it in the try block. But for simplicity, we wrote like that. If try block run then else block will also run. It doesn't matter whether there is an error or not, the final block will always work.

Example:5
Input
def divide(a,b):
  try:
    return a/b
  except ZeroDivisionError:
    print("You can divide a number by zero")
v=int(input("Enter first number:"))
z=int(input("Enter second number:"))
print(divide(v,z))
Output
Enter first number:5
Enter second number:0
You can divide a number by zero

CodersAim is created for learning and training a self learner to become a professional from beginner. While using CodersAim, you agree to have read and accepted our terms of use, privacy policy, Contact Us

© Copyright All rights reserved www.CodersAim.com. Developed by CodersAim.