Python Try Except

Using Python try except with examples, we will discuss Python try except so that you can learn more about it.

Exceptions can be handled with try and except. During the execution of a program, there may be exceptions. The term “exception” refers to errors that occur when a program is being executed.

Python Try Except

The Python interpreter will not inform you if there are any syntax errors (grammar faults), but it will terminate without warning.

With Python try except, the try block can be used to test a block of code for errors.

When an error occurs, you can handle it with the except block. If there is no error, you can execute code in the else block.

No matter what the try- and except blocks say, the finally block will execute the code.



Python Exception Handling

Normally, Python will generate an error message if an error occurs, or exception as we call it.

Python try except can be used to handle these exceptions:

There will be an exception thrown because mrx is not declared in the try block:

Example

try: print(mrx) except: print("An exception occurred")

Due to an error in the try block, the except block will be executed instead.

Try blocks prevent the program from crashing and raising errors:

The following statement will raise an error because mrx is not specified:

Example

print(mrx)

Else

The else statement can be applied to create a block of code that is executed if no errors are raised:

Here, there is no error generated by the try block:

Example

#Try raises no errors, so else is executed: try: print("First Learn Python") except: print("There is something wrong") else: print("This msg is printed by else.")

Python Many Exceptions

Using Python try except, you can create as many exception blocks as you want. For example, if you would like to execute a special block for a specific error:

You should print one message if NameError is thrown and another if other errors are thrown:

Example

#Because mrx is not specified, the try block will generate a NameError: try: print(mrx) except NameError: print("Variable mrx is not declared") except: print("There is an error")

Raise an exception

An exception can be thrown by a Python developer if a condition is met.

Exceptions are thrown (or raised) using the raise statement.

In the case of mrx below zero, stop the program and raise an error:

Example

mrx = -1 if mrx < 0: raise Exception("The number below 0 is not possible")

Exceptions are raised by the implementation of the raise statement.

There is the option to define the type of error to raise, and the text to be printed to the user.

A TypeError will be raised if mrx is not an integer:

Example

mrx = "Learn Python" if not type(mrx) is int: raise TypeError("Integers are the only acceptable values")

Finally

Regardless of whether the try block raises an error, the finally block will be executed.

Execute

Example

#Even if there are errors in the try block, the finally block gets executed: try: print(mrx) except: print("There is something missing.") finally: print("The 'try except' is finished")

When closing objects and cleaning up resources, this can be beneficial:

Open and write to a non-writable file:

Example

#If a read-only file is attempted to be written to, the try block will raise an error: try: f = open("unreadablefile.txt") try: f.write("Elon Musk") except: print("The file could not be written because of an error") finally: f.close() except: print("There was a problem opening the file")

File objects do not need to remain open for the program to continue.


Python Try Except Benefits

Following are some benefits of using try-except in Python:

  1. By using try-except, you can gracefully handle errors and exceptions that would otherwise cause your program to terminate abruptly. Instead of crashing, you can catch specific exceptions and take appropriate actions, such as displaying an error message, logging the exception, or attempting to recover from the error.
  2. try-except enhances the robustness of your code. It allows you to anticipate and handle potential errors, ensuring that your program can handle unexpected situations without crashing. This is especially important when working with external resources, network operations, or user input, where errors can occur frequently.
  3. With try-except, you have more control over the flow of your program. You can catch exceptions and execute alternative code paths, allowing your program to continue execution even if certain operations fail. This enables you to handle errors and continue executing the program logic as desired.
  4. try-except provides the ability to capture and handle exceptions in a controlled manner. You can log or report the occurrence of exceptions, including relevant information about the error, such as the stack trace or specific error messages. This helps in debugging and troubleshooting issues, making it easier to identify and resolve problems in your code.
  5. Python allows you to catch specific types of exceptions using different except blocks. This gives you fine-grained control over handling different types of errors individually. You can choose to handle specific exceptions differently based on their nature, allowing for more precise error handling and recovery strategies.
Leave your reaction below, and let’s work together to make this site an exceptional place for all.
We value your feedback.
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0

Subscribe To Our Newsletter
Enter your email to receive a weekly round-up of our best posts. Learn more!
icon

Leave a Reply

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