Python Exception Handling: Try....Catch....Finally Statement

Python Exception

We all know that all the programming languages generate errors. Errors can be two types: logical error and syntax error. Exception handling is a key feature of all object-oriented programming languages. To handle any unpredicted error, Python delivers two significant features. This is used for restoring capabilities. Exception Handling, we will learn about this topic in this tutorial. It has three major components: try, except, and finally. The try block is used to test the code blocks for errors. Except block is used to handle the error. The finally block will not consider the try and except code. By default, it will run its own block of code.

Exception Handling

Python will usually break working when a fault occurs or exception calls. That time is will print an error message. The try statement is used to handle all the exceptions. An example is given below,

try:
  print(i)
except:
  print("Exception")

In the above code, it will print the exception part because i is not defined. When the try block gives an error, the compiler moves to except part and run that block of code.  But try block is necessary for exception handling. Without try block, I will print give an error. Example,

print(i) #error

More than One Exceptions

There is no restriction to create more than one except block. It depends on the program requirement. Programmers can define as many except block as they want. An example is given below,

 try:
  print(i)
except NameError:
  print("i is not defined") # It will print this line because it’s a name error

#i is not defigned

except:
  print("Else")

If we change the name error to value error, then it will print only except block i.e. Else.

Else Statement

We can use the else statement instead of the last except block. It means if no error has occurred, it will simply print the else part. An example is given below

try:
  print("Python")
except:
  print("Exception")
else:
  print("Code is Perfect")

# This code will print both the try block along with the else part i.e. Python
# Output:
# Code is Perfect

Finally Block

This block will not care about the try and except block. By default, it will execute its own block of code. In the below two codes, we will compare the try block with the finally block and except block with the finally block.

Sample Code 1:

try:
  print(i)
except:
  print("except") # Without finally, this line will print
finally:
  print("This is finally done") # It will print both the except and finally block

Sample Code 2:

try:
  print("Python") # Without finally this line will print
except:
  print("except")
finally:
  print("This is finally done") # It will print both the try and finally block

Exception Raise

It’s completely the developer’s choice to throw an exception if a condition is not met. The raise keyword is used to throw an exception. We can mention the type of exception as well. Examples are given below,

i = 5
if i > 0:
  raise Exception("Condition Mismatch")

p = 100
if type(p) is int:
  raise TypeError("Sorry") 

List of standard Exceptions and its descriptions are given below,

Name Description
Exception For base-class exception
SystemExit sys.exit() 
StandardError For base-class except for Standard Error
ArithmeticError For numeric calculation exception
OverflowError Limit for Numeric calculation exception
AssertionError For assert statement
EOFError For input() function and end of file
AttributeError For attribute failure
ImportError Failure of the import statement
KeyboardInterrupt Interrupts execution by keyboard interruption
IndexError For invalid indexing
KeyError For invalid key value
NameError For an invalid identifier
EnvironmentError For outside environment
IOError For OS error
SyntaxError Related to Python syntax
SystemError For Internal or compiler problem
ValueError For Invalid value
TypeError For invalid data type
RuntimeError For category mismatch