Loop Control Statements in C Introduction to HTML How to use the Github API The image tag, anchor tag and the button tag Ordered and Unordered Lists in HTML The division tag HTML Forms Tables in HTML Introduction to C Programming Introduction to Python Varibles and Datatypes in Python Operators in Python Typecasting in Python Input and Output in Python If Else in Python Loops in Python Break, Continue and Pass in Python Python practice section 1 Lists in Python Tuple in Python

Exception handling in python

Exception handling means preventing a program to throw an error and crashing in between. If an app or a website stops unexpectedly when the user is performing some operation, then it can lead to confusion and other problems. Since the normal user is not a technical person who knows what that error means so if an operation fails then we must output a user-friendly message on the screen so that the user can know what the problem is. Python provides a way to deal with this. Let's see how we can do it.

What is an exception?

Exceptions are errors that occur during run-time. There are various types of exceptions. Some of them are given below.
Exception Cause
IndexError It occurs when iterating through a sequence, and we go out of the range.
KeyError It occurs when a given key is not found in the dictionary.
ZeroDivisionError It occurs when you try to divide a number by zero.
NameError It occurs when a given variable is not found.
FileNotFoundError It occurs when a file you are trying to open does not exist. (not found in the given path)
For example - If we use a variable without declaring it,

a=4
print(b)
Output
NameError: name 'b' is not defined  
And if we go out of range in a sequence,

li=['Rapid', 'Coders']
for item in range(0,3):
    print(li[item])
Output
Rapid
Coders
Traceback (most recent call last):
    File "c:\Users\HP\OneDrive\Desktop\aditi jain\Rapid Coders Articles\python.py", line 3, in 
    print(li[item])
IndexError: list index out of range

Handling exceptions with try-except

Using try-except statements we can prevent our program from unexpected errors. The statements which are most likely to generate an exception are put inside the try block. The statement(s) inside the except block are executed only when any statement in the try block generates an exception.

stud_marks={'Rakesh':89,'Parul':97}
name=input("Enter student to search marks for : ")

try:
    # if student found, print his/her marks
    print(stud_marks[name])

except:
    # otherwise display student not found on the screen
    print(f"Student with name '{name}' does not exist")
    
Output
Enter student to search marks for : Parul
97
Enter student to search marks for : Akshay
Student with name 'Akshay' does not exist.
        

Handling multiple exceptions

Sometimes the same piece of code can raise different types of exceptions during run-time and we may want to deal with every exception in a different manner. This can be done by using separate except blocks(for each exception) with the try block. At one time, only one except block will be executed. The syntax for this is as follows:
try:
     # Statements

except ExceptionName1:
     # Statements

except ExceptionName2:
     # Statements

except ExceptionNameN:
     # Statements

# where ExceptionName can be KeyError, IndexError, ZeroDivisionError, etc.
For example -

stud_marks={'Rakesh':89,'Parul':97}
try:
    with open("thought.txt", 'r') as f:
        content=f.read()
        print(content)

    name=input("Enter student to search marks for : ")
    print(stud_marks[name])

except FileNotFoundError:
    print("Cannot open student.txt")

except KeyError:
    print("Student not found")

except:
    print("Sorry for inconvenience. Please try again later.")
If the thought.txt file is not found, then the FileNotFoundException gets raised that is handled by the except FileNotFoundError block that prints "Cannot open thought.txt". Otherwise, if the student is not found, then it goes to the except KeyError block and prints Student not found. However, if some other exception other than FileNotFoundError or the Keyrror is raised, then it is handled by the last except block that prints "Sorry for inconvenience. Please try again later."
In this way, we can handle multiple exceptions.

Finally keyword

The finally keyword is used with try-except. When the try or the except block gets executed, then the statements inside the finally block are executed.

a=int(input("Enter first number : "))
b=int(input("Enter second number : "))

try :
    result=a/b

except ZeroDivisionError:
    result="Cannot divide by zero"

finally:
    print(result)
Output
Enter first number : 5
Enter second number : 0
Cannot divide by zero
    
Enter first number : 4
Enter second number : 2
2.0 
    

Assert Keyword

The assert keyword used to raise custom exceptions.

a=int(input("Enter your age : "))

# if the assert condition is true, program terminates successfully
# otherwise, exception is raised.

assert a>=18 and a<=60

print(f"Your age is {a}")
The assert keyword raises the exception AssertionError.
Enter your age : 70
Traceback (most recent call last):
  File "c:\Users\HP\OneDrive\Desktop\aditi jain\Rapid Coders Articles\pytho.py", line 3, in 
    assert a>=18 and a<=60
AssertionError
The AssertionError exception can be handled using try-except.

a=int(input("Enter your age : "))

try:
    assert a>=18 and a<=60
    print(f"Your age is {a}")

except AssertionError:
    print("Age must be >= 18 and <= 60")
    
Output
Enter your age : 70
Age must be >= 18 and <= 60