Exceptions and Errors in Python – Different Exceptions and their Handling in Python

When we write a program, we can make mistakes that cause errors when we run it. When a Python program meets an unhandled error, it terminates. These errors can be divided into two categories:

  1. Syntax Errors
  2. Logical Errors(Exceptions)

Syntax Errors:

Syntax error or parsing error refers to an error caused by not following the right structure (syntax) of the language.

For Example:

numb = 10
if(numb > 0)    # colon(:) is missing here 
print("positive number")
else:
    print("Negative number")

Output:

 File "/home/ba12f4db06be8a7ce06b7796040d87d0.py", line 2
    if(numb > 0)
               ^
SyntaxError: invalid syntax

An arrow in the example indicates where the parser encountered the syntax problem.

We can see that there is no colon: in the if statement in line 2

Logical Errors(Exceptions):

Exceptions or logical errors are errors that occur at runtime (after passing the syntax test).

An exception is a condition in a program that interrupts the flow of the program and causes the code to stop running. Python has a fantastic approach to handling exceptions so that the code runs without problems or disruptions.

For example, they occur when we attempt to open (read) a file that does not exist (FileNotFoundError), divide an integer by zero (ZeroDivisionError), or import a module that does not exist (ImportError).

Python generates an exception object if these types of runtime issues occur. If the error is not handled appropriately, it prints a traceback to the error as well as some information about why the issue happened.

Exceptions can be either built-in errors/exceptions or bespoke exceptions.

The following are some examples of common in-built exceptions:

  • ZeroDivisionError
  • NameError
  • IndentationError
  • IOError
  • EOFError

 Python test Exception Creation

For Example:

gvn_num1 = int(input("Enter 1st number = "))
gvn_num2 = int(input("Enter 2nd number = "))
print("The division of (1st number/2nd number) =  ")
print(gvn_num1/gvn_num2)

Output:

Enter 1st number = 6
Enter 2nd number = 0
The division of (1st number/2nd number) = 
Traceback (most recent call last):
File "jdoodle.py", line 4, in <module>
print(gvn_num1/gvn_num2)
ZeroDivisionError: division by zero

Handling Exceptions by try -except Blocks in Python

We use try-except statements to avoid errors from occurring and halting the program’s progress. The entire logic of the code is contained within the try block, and the except block handles conditions where an exception/error occurs.

Syntax:

try:
    # block of code
except <Exception Name>:
    # block of code
# Rest of code

How to Handle ZeroDivisionError in Python?

try:
    gvn_num1 = int(input("Enter 1st number = "))
    gvn_num2 = int(input("Enter 2nd number = "))
    print(gvn_num1/gvn_num2)
except ZeroDivisionError:  # exception name for handling it
    print("The Denominator cannot be zero.Enter a valid number")

Output:

Enter 1st number = 5
Enter 2nd number = 0
The Denominator cannot be zero.Enter a valid number

NameError Exception:

In Python, there are various standard exceptions, one of which is NameError. When the identifier being referenced is not declared in the local or global scope, a NameError is thrown. NameError can be caused by a variety of factors, including:

1. When built-in function is misspelled

num = int(input("Enter number = "))
prnt(num)

Output:

Enter number = 3
Traceback (most recent call last):
File "jdoodle.py", line 2, in <module>
prnt(num)
NameError: name 'prnt' is not defined

Here print is misspelled

2. Using variables that aren’t defined

gvn_str = input("Enter string = ")
print(gvn_string)

Output:

Enter string = hello
Traceback (most recent call last):
File "jdoodle.py", line 2, in <module>
print(gvn_string)
NameError: name 'gvn_string' is not defined

Here gvn_string is not defined, we gave gvn_str.

3. Defining a variable after its use

print(gvn_str)
gvn_str = input("Enter string = ")

Here we get Name Error since gvn_str is defined after it is used.

4. Incorrect use of scope.

How to Handle NameError Exception in Python?

try:
    gvn_str = "hello"
    print(gvn_string)
except NameError:
    print("NameError Exception. Please check ")

Output:

NameError Exception. Please check

The following are some of the most common built-in exceptions in Python programming are

AssertionError, FloatingPointError, ImportError, AttributeError, OverflowError, OSError etc

Conclusion

You now have an introduction to exceptional handling, and I hope you understand the fundamental concepts of exception handling.