Exception Handling in Python

Here you will be learning about Exception handling in python and methods to handle different exceptions.

Exception Handling in Python

Exception Handling in python is used to handle the errors.

The errors in Python are of two types
1.Syntax Errors
2.Exceptions

  • Errors are problems in a program due to which the program will stop the execution
  • Exceptions are raised when some internal events occur which change the normal flow of the program.

Difference between Syntax Errors and Exception

Syntax Error:

  • This error is caused by the wrong syntax in the code. It leads to the termination of the program.
  • Wrong syntax may be like
    Missing colons
    Indentation error
    Misspelling
    Misusing python keywords etc

Different  types of Exceptions in Python:

Exceptions in python are caused due to many errors.

Type Error : This exception is caused due to the operation or function applied to wrong type of object.
Example:

a = "b" + 5

In the above example the code raises an type error because an integer cannot be added to a string.

Syntax Error: This exception is caused due to the  syntax error in the code.
Example:

if(a>b)
print("a is greater than b")

In the above code it raises an syntax error because if statement should be followed by a colon(“:”).

Index Error : This exception is caused when the index is out of range. It is mainly caused in sequence types like list, tuple etc.

list = [1,2,3]
a =  list[4]
print(a)

The above code raises an Index Error because list does not contain index 4.

Import Error : This Exception is raised when interpreter is failed to import a library or module.

Name Error : This Exception is raised when method or variable is not in the scope.

Key Error : This Exception is raised when key is not found in dictionary.

Handling Exceptions : 

Try and except statements are used to catch and handle exceptions.

try block : code that might raise an exception is put inside “try” block.
except block : the code in this block handles exception
else block : code that runs if no exceptions are raised
finally block : this block of code runs always irrespective of the block executed.

try:
# Code that may raise an exception
result = 10 / 0
except Zero Division Error:
# Code that runs if a Zero Division Error occurs
print("You can't divide by zero!")
else:
# Code that runs if no exceptions occur
print(f" Result is {result}")
finally:
# Code that runs no matter what
print("This will always execute")

the above code illustrates the working of try, else and finally statements, it is used to handle zero division exception.

 

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top