top

Search

Python Tutorial

.

UpGrad

Python Tutorial

Python Try Except

Introduction 

Python is an object-oriented, interpreted, high-level, dynamically semantic programming language. It is particularly desirable for quick application development and for usage as a glue language or scripting language to tie existing components together due to its high-level built-in data structures, dynamic typing, and dynamic binding. Python's straightforward syntax emphasizes readability and makes it simple to learn, lowering the program's maintenance cost.

Overview

A circumstance that develops while a program is being run is referred to as an exception. It serves as a warning that something unanticipated occurred. In Python, exceptions are represented by an object of a certain type.

All built-in exception handling in Python that does not cause the system to quit derives from the Exception class. Exceptions have descriptive names of their own. For instance, you will get a Zero Division Error exception, which is a subclass of the Exception class, if you attempt to divide a number by zero. 

Exceptions can be handled with the try-except statement. The execution of a program could result in exceptions. Exceptions are mistakes that occur while the program is running. Python will immediately stop if it encounters issues such as syntax errors (grammar faults). The end user and developer both suffer from a sudden exit. You can effectively address the issue by using a try-except statement rather than an emergency halt. If you don't handle exceptions correctly, an emergency halt will occur. 

What is try except in Python?

We can raise an exception in Python when an unexpected occurrence happens. Python halts execution when an exception is raised and begins looking for an exception handler that can handle it. An exception handler is what, then? The try-except clauses are useful in this situation.

It's crucial to develop programs that can gracefully handle particular mistakes or exceptions. Furthermore, the error or exceptions must not result in a fatal error that forces your program to crash. A code block known as a Python try-except exception statement enables your program to execute several actions in the event of an error.

Here is how you construct a try-except statement: 

try:
    code block 1
except ExceptionName:
    code block 2
Syntax of a try-except statement in Python
try:
    # Some Code
except:
    # Executed if error in the
    # try block 

Python will first try to run the try statement's (code block 1) code. If no exception arises, the try statement is completed and the except statement is not executed. The remainder of the clause is omitted in the case of any exception. The code in the except statement will then be run (code block 2) if the exception type satisfies the exception defined following the except keyword (ExceptionName). The program will continue to run the remaining lines of code beyond the try-except code blocks if nothing in this block stops it. The exception is forwarded to outer try statements if it does not match the ExceptionName. If no other handler is discovered, the execution terminates with an error.

The try-except block's principle is as follows:

  • Try: the program that contains the Python catch exception. If an exception occurs, it enters the except block immediately.

  • Except: if an exception occurred in the try block, only then would this code be run. Even if a try block just has a pass statement, the except block is still necessary.

It is possible to combine it with the finally and else keywords.

  • Else: Only if no exceptions were raised in the try block is code in the else block performed.

  • Finally: Whether or not an exception was triggered, the code included in the finally block is always carried out.

Example 1 - Capturing the exception.

x = '6'
try:
    if x > 3:
        print('X is larger than 3')
except TypeError:
    print("Oops! x was not a valid number. Try again...")
Oops! x was not a valid number. Try again...

Example 2 – Handling exceptions using try and except 

try:
    numerator = 10
    denominator = 0

   result = numerator/denominator
    print(result)

except:
    print("Error: Denominator cannot be 0.")

# Output: Error: Denominator cannot be 0. 

In the above illustration, we're attempting to divide an integer by zero. This code causes an exception in this case. The try block contains the code result = numerator/denominator, which is used to handle exceptions. The remaining code in the try block is now skipped when an exception occurs.

Statements contained within the except block are carried out after the exception is caught. The except block is skipped if none of the statements in the try block raise an exception.

How does try() work? 

First, the code between try, or the try clause, is performed. Only the try clause will be executed if there doesn't exist an exception, unless when the clause is finished. The try clause shall be skipped and the except clause will take effect if any exception occurs. Any exception that arises but isn't handled by the codes except the clause is passed on to the outermost try statements. The execution halts if the exception is not handled. There can be more than one unless clause in a try statement.

Python will throw an exception error when syntactically correct code encounters a problem. If this exception error is not handled, the program will crash. Using the except clause, you can control how your program handles exceptions.

You may better understand the try and except block by using the following function:

def linux_interaction():

    assert ('linux' in sys.platform), "Function can only run on Linux systems."

    print('Doing something.')

Only a Linux machine is capable of running the linux_interaction(). If you call the assert in this function on a platform other than Linux, an AssertionError exception will be raised.

The following code can be used to test the function:

try:
    linux_interaction()
except:
    pass

You corrected the mistake here by issuing a pass. If this code were executed on a Windows computer you will get a blank code. The fact that the program didn't crash is a plus in this situation. However, it would be useful to know if an exception of any kind was thrown each time your code was executed. To do this, you can modify the pass so that it produces an educational message as follows: 

try:
    linux_interaction()
except:
    print('Linux function was not executed')

Run the following code on a Windows computer:

Linux function was not executed

When a program calling this function encounters an exception, the program will still run and let you know that the function call was unsuccessful. The kind of error that was thrown because of the function call was not visible to you. In Python catch all exceptions and the errors that the program threw to determine precisely what went wrong.

Else Clause in Python 

In real life, there are times when we must make choices, and based on those choices, we determine what to do next. Programming encounters similar scenarios where we must make choices and then carry out the following block of code following those choices. Programming languages use decision-making statements to control the direction (or Control Flow) of program execution. The conditional statements that Python try except continue offers are listed below. 

  • if

  • if..else

  • Nested if

  • if-elif statements.

In conditional statements (if statements), the else keyword determines what to execute if the condition is False. You can tell a program in Python to run a particular block of code only if there are no exceptions by using the else statement.

In addition to blocks, the else keyword can be used in try; an example is provided below.

Example 1 – 

To specify what to do in a try...except block, if no errors were raised, use the else keyword:

x = 5

try:
  x > 10
except:
  print("Something went wrong")
else:
  print("The 'Try' code was executed without raising any errors!")

Example 2 –

# program to print the reciprocal of even numbers
try:
    num = int(input("Enter a number: "))
    assert num % 2 == 0
except:
    print("Not an even number!")
else:
    reciprocal = 1/num
    print(reciprocal)

Output – If we pass a number 

Enter a number: 1
Not an even number!

If an even number is passed, the reciprocal is calculated and shown. 

Enter a number: 4
0.25

If we do so, we receive a ZeroDivisionError since the previous exception does not handle the code block inside else. 

Enter a number: 0
Traceback (most recent call last):
  File "<string>", line 7, in <module>
    reciprocal = 1/num
ZeroDivisionError: division by zero

Finally Keyword in Python

There may be instances in programming where the current approach fails to handle some exceptions. However, the procedure could need a few further steps before it is finished, such as closing a file or a network. Python offers a keyword finally to address these circumstances, and it is always performed after try and except blocks. The finally block is always executed after the try block has ended normally or after the try block has ended unexpectedly.

Syntax – 

try:
       # Some Code.... 
except:
       # optional block
       # Handling of exception (if required)
finally:
      # Some code .....(always executed)    

The final statement is always carried out following the try statement. After the finally block has been executed, any exceptions that were not handled by the except block are raised again. To deallocate the system resources, the block is used. Finally can be used directly after a try without requiring an except block, no exception handling is done in that scenario. 

Let’s look at some examples:

Example 1 –

# Python program to demonstrate finally
# No exception Exception raised in try block
try:
k = 5//0 # raises divide by zero exception.
print(k)
# handles zerodivision exception
except ZeroDivisionError:
print("Can't divide by zero")
finally:
# this block is always executed
# regardless of exception generation.
print('This is always executed')

Output:

Can't divide by zero
This is always executed

Example 2 – 

# Python program to demonstrate finally
try:
k = 5//1 # No exception raised
print(k)
# intends to handle zerodivision exception
except ZeroDivisionError:
print("Can't divide by zero")
finally:
# this block is always executed
# regardless of exception generation.
print('This is always executed')

Output:

5

This is always executed 

Conclusion 

Python frequently causes programmers to fall in love due to the enhanced productivity it offers. The edit-test-debug cycle is extraordinarily quick because there is no compilation step. Python programs are simple to debug because a segmentation failure is never caused by a bug or incorrect input. Instead, the interpreter raises an exception when it finds a mistake. The interpreter generates a stack trace if the program doesn't catch the exception. Setting breakpoints, evaluating arbitrary expressions, inspecting local and global variables, stepping through the code one line at a time, and other features are all possible with a source-level debugger. 

FAQs

1. What does a try-except statement aim to achieve?

With the help of the try-except statement, a feature added by Microsoft to the C language, programs can take over an execution-ending program when certain circumstances arise.

2. What are the two try types used outside of Python?

In Python, there are two different sorts of errors: syntax errors and exceptions.

3. What is the “finally” keyword in Python?

No matter if there is an exception or not, the finally keyword is used to run code (used with exceptions - try.. catch statements).

4. Is Python's else a command?

The block of code that runs if the conditional phrase in the if statement evaluates to 0 or a FALSE value is included in an else statement. Following if, there can only be one possible else statement, which is an optional statement.

5. In Python, can an except block be empty?

A programmer may have intended to deal with the exception but never created the necessary code if the except block is empty.

Leave a Reply

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