Python Exception Handling: Try, Except, and Finally

    Every programming language has its own way of dealing with errors and exceptions. It is called exception handling.

    In this tutorial, we will discuss Python exception handling. We will explain how to tackle if any exception occurs in a Python program. We will also learn all the ways to handle exceptions in Python, namely try, except, and finally.

    Python Exception Handling

    Allowance Handling

    Exceptions are the unexpected errors that occur in the program at the time of execution. Exception handling is a mechanism that detects the exceptions in the code and separates them from the rest of the code, so the program execution does not come to a halt. In Python, we can use try, except, and final statements to handle the exceptions.

    Catching Exception

    We use try and except keywords to catch an exception in Python and throw as an alternate way to deal with the exception. Inside the try statement block, we write a code that could run into an exception during the run time, and if an exception occurs, the exception statement block gets executed. What if no exception occurs in the try block?

    If there is no exception in the try block, then the except block won’t execute.

    try….except Syntax

    try:
    
        #try block
    
    except:
    
        #except block

    Code Example:

    for i in [2,1,0,3]:
        try:
            print(2/i)
        except:
            print("There is an exception in the try block because we are dividing 2 with",i )

    #Output

    1.0
    
    2.0
    
    There is an exception in the try block because we are dividing 2 with 0
    
    0.6666666666666666

    Behind the Code

    Here, in the above example, when i iterates through the list [2,1,0,3] and when its value becomes 0, it divides 2. Thus, this raises a ZeroDivisionError, and so the except block gets executed.

    Catch a Specific Error

    We can pass some specific kind of error along the except statement so that it only gets executed when the try block throws that same error. We use tuple and set errors as its elements when we want to specify more than one error with the except method.

    Code Example:

    try:
        print(int("techgeekbzz"))
    
    except ZeroDivisionError:
        print("the try statement has zero divison error")
    
    except ValueError:
        print("The try block has value error")

    #Output

    The try block has value error

    Raise an Error

    In Python, we have the raise keyword that is used to create an error. We can also pass a message along with the error so the user can understand why specifically this error is raised.

    Syntax

    raise Error_name(“message”)

    Example:

    raise ValueError ("There is a Value Error in the program")

    #Output:

    ValueError: There is a Value Error in the program

    try……..finally

    With the try and except statements, we can also add a finally statement. The code inside the finally block will execute in every case, no matter whether the try or except statements execute or not.

    finally Syntax:

    try:
        # try block
    except:
        # except block
    finally:
        # finally block 

    Code Example:

    try:
        print(3/0)
    
    except:
        print("there is an error in the try block")
    
    finally:
        print("it will always execute")

    #Output

    there is an error in the try block
    
    it will always execute.

    Conclusion

    That was all about exception handling in Python. An exception is an error in code that has the potential to halt program execution. With exception handling, we can ensure that our program runs correctly even when it comes across an exception.