The intuitiveness and implicit qualities of Python comes with a small price, errors and exceptions for minor violations are very common in Python. Most of the time a simple indentation or a spacing error can result in an exception or error being raised. Exceptions is essentially another name for errors that pop-up in Python while programming tasks and functions. 

Handling exceptions is just as important as avoiding them in the first place, sometimes there are scenarios where the exception is not dependent on the code but the input that it receives. That input can be variables, files or directories, a variable can receive invalid values, a file opened can be empty or non-existent and a browsed directory might simply just not exist on another system where the program might be running. An exception raised in such a scenario will make a program exit without executing further on, making the program very unsuitable for use.

To avoid the program from exiting due to an exception, some methods are used to limit or contain these exceptions so that the code can execute further or alternative paths. One of the most popular methods of exception handling is the try & except method:

Try & Except

The ‘try’ clause works by initially running the block of code inside and if there is an exception raised, it will simply move on to the ‘except’ clause without exiting and then the block of code inside the except clause will be executed.

try:
   f1 = open("text.txt", 'w') #If the command raises any exception or error due to the unavailability or the emptiness of the file, it will redirect to the except clause otherwise it will open the file.

except:
    print("There is an exception") #This will print the statement along with the exception code but it will continue to the code written after the except clause.
    

Try, Except & Finally

Since the use of try and except is already discussed, it tries the code and if it executes, it will move on to the rest of the code otherwise it will redirect to the except clause. In the case of the ‘finally’ clause, it will be executed no matter if the try clause is successfully executed or not. The ‘finally’ clause depicts the final action after the try and except clauses are executed and after it is executed, it will move on to the rest of the code.

try:
   f1 = open("text.txt", 'w') #If the command raises any exception or error due to the unavailability or the emptiness of the file, it will redirect to the except clause otherwise it will open the file.

except:
    print("There is an exception") #This will print the statement along with the exception code but it will continue to the 'finally' clause after the except clause.

finally: 
    f1.close()
    print("The Try & Except method is finished here") #This will determine the action in lieu of the aftermath of the try and except clause.
    

Customized Exceptions

You can also raise custom exceptions apart from the try & except method using the raise function, there is an amplitude of available keywords for exceptions that are used for certain situations.

a = "Hi"
b = 66.7

if not type(a) is float:
       raise TypeError("Only float is allowed") #Here, in the current scenario, the system will raise the TypeError with a statement that reads "Only float is allowed" and then continue with the rest of the code, if there is no error to be raised then the code will move to else.

else:
      c = a + b
      

Numerous Exceptions

You can declare specific exceptions in the except clause. If that specific except clause with the specific exception is not fulfilled then the system will move on to the next except clause.

a = "Hello there"
b = 10

try: 
   c = a + b

except TypeError:
    print("Unsupported mathematical operation between two invalid operands")

except:
    print("Unknown error")
    

Else With Try & Except

You can use the else clause with the try and except method:

x = 50
y = 10

try:
   c = a + b

except:

    print("There is an error")

else:
   print(" \n The answer to a + b is: ", c) #If there is no exception raised by the except clause then the system will directly move to the else clause.
   

Categorized in: