Free Python Tutorial – Nested Error Management, Error Calling, Finally Block

In the last issue of Python Tutorial we learned how to use exception arguments to better manage errors. We also learned how to manage errors through multiple blocks and individual blocks except.

Nested error management blocks in Python 

Sometimes you have to put an error management routine inside another block. When you use nesting error management routines, Python will first go to the most internal routine and then go to earlier routines.

Python allows you to use nesting error management routines to suit your needs. But why use nesting error management routines?

Some of the things you want to do are get input from the user and use the information in a circle. Before the information is put into a circle, you must first verify their authenticity.

But how can we use error management blocks in a common way in Python ? Consider the following example:

1.IDLE Open and select New File from the File menu.

2. Insert the following code snippet into the new window.

TryAgain = True

while TryAgain:

try:

Value = int (input (“Type a whole number.”))

except ValueError:

print (“You must type a whole number!”)

try:

DoOver = input (“Try again (y / n)?”)

except:

print (“OK see you next time!”)

TryAgain = False

else:

if (str.uppe (DoOver) == “N”):

TryAgain = False

except KeyboardInterrupt:

print (“You pressed Ctrl + C”)

print (“See you next time!”)

TryAgain = False

else:

print (Value)

TryAgain = False

The above code snippet starts with a loop in Python .

(In the next article we will go into the Python looping topic.) Now understand that loops are used to perform a number of similar tasks.

 Applications often use circles as you see above, because in an application, especially when an input from the user is to be received, the circles are repeated as long as the user does not enter the correct value.

The above loop has a simple pattern and is repeated to repeat a set of commands as long as the user input does not end the loop.

When this field is executed, the application will ask the user to enter an integer. This number can be any integer. If the user enters an incorrect value or presses Ctrl + C or any key that causes an interruption, the code is executed to handle the defined error and will address the issue.

 But if the user enters the correct value, the program prints the entered value and adjusts the TryAgain variable value to False to end the loop execution.

The ValueError error will be triggered when the user makes a mistake.

Because you don’t know two things. The first is whether the user will enter the correct value and the second whether the user wants to continue the program or terminate the program.

That’s why you’re asking him about continuing. Be careful though, if the user enters more than one entry, another error will occur. Internal try-except blocks are used to manage the user’s second input.

Note that in the second block we used str.upper () function to process user input which is a character for both big and small y or y.

When you ask a user to enter a character, it is a good idea to compare both the upper and lower case characters or strings so that errors can be easily managed.

3. Save the program and select Run Module from the run menu. The application asks the user to enter an integer.

4. Type Hello and press the Inter key. The program will display a managed error and, unlike the programs you have written so far, will ask you if you would like to enter another value. This question again arises because we used the While loop.

5. Press the Y key to prompt the program twice to enter the complete number.

6. Type 5.5 and press the Enter key. The second time program will display a controlled error message asking you if you would like to enter a second time number.

7. Press Ctrl + C or any key to make a break. Note that the managed error message that appears appears from within the internal error management loop. The error handling program will never go to the external error management block because the internal error handling block manages it.

Execute Exceptions

In the past few issues we have cited examples that were all a reaction to a gross mistake. Mistakes that may occur by any user.

An error occurs when a problem occurs for an application. However, in some cases you may not know exactly how to manage it when running an application when an error occurs.

You may not succeed at one level properly managing one error and you would prefer to manage it at another level.

 In short, in some cases you have to manually call an error. The following snippet shows how to call and respond to an error in your application.

1.IDLE Open and select New File from the File menu.

2. In the new window, enter the following code snippet.

try:

raise ValueError

except ValueError:

print (“ValueError Exception!”)

You may never write such a code in the real world, but this piece of code shows you how to call an exception manually at your most basic level.

In the above code snippet, the error calling command is located inside the try… except block.

In a simple call, the exception name is specified along with the raise keyword. You can use arguments manually as part of the output that is supposed to provide additional information.

 Note that this try… .except block is missing an argument, because there is no further work to be done after the call. You rarely use manual calling, but you should know how to manually call.

Note that in such circumstances the use of the other section is optional and not necessary. But at least you need to define an except block. You will see the following output by running the program.

Sending error information to a caller

Python provides you with an extremely flexible error management that allows you to send error information to an error caller, no matter what error you used.

 More precisely, submit the error details for the code that manually called for an error.

Sending Extra Information helps you show additional information when displaying a generated error that helps you or the person working on a project find out more about the error that has occurred.

Note the example below to clarify the discussion.

1.IDLE Open and select New File from the File menu.

2. In the new window, enter the following code snippet.

try:

Ex = ValueError ()

Ex.strerror = “Value must be within 1 and 10.”

raise Ex

except ValueError is as follows:

print (“ValueError Exception!”, e.strerror)

The ValueError exception / error does not normally have a property called strerror, but you can simply add and exempt such a property with the exception.

When you run the example above, the program generates a managed error that calls the except block to handle the error, but you must use the e attribute to access the error information.

The print command then uses the variable e and the strerror property to display a managed error.

3. Save the application and select Run Module from the Run menu. The output of the above code snippet is shown below.

The above technique is helpful as it allows you to manually add additional and additional information when calling errors.

Build and Apply Custom Exceptions

Python allows you to create and use custom custom error management blocks. This model of exceptions gives you great flexibility and even allows you to edit exceptions to suit your needs.

In the previous paragraph, we showed you how to send information to an exception caller and edit the ValueError exception with additional data.

However, sometimes you have to create a custom exception, as your application may produce a specific error.

For example, the name of an exception may not give the viewer clear information about the error or may not provide you with a specific error management when working with databases and special services.

We are not now going into the implementation of custom exceptions to explore the concept of classes.

Applying finally block

Typically, you plan to manage any exceptions that occur suddenly. However, sometimes you can’t fix all the problems and your program will end abruptly.

At this point, your goal is to fix a problem that causes users who use your app to lose their data.

The best way to manage your errors is to preserve data that may be suddenly lost. The finally block lets you design a strategy when the application crashes.

You can use the finally block to execute commands that will be executed at the last minute. Typically the finally block contains brief information that contains only vital commands.

 Closing the files that are open, removing the user from the program, and other tasks that are required to complete the program are included in this block.

Consider the following example to clarify:

1.IDLE Open and select New File from the File menu.

2. Insert the following code snippet into the new window.

import sys

try:

raise ValueError

print (“Raising an exception.”)

except ValueError:

print (“ValueErro Exception!”)

sys.exit ()

finally:

print (“Taking care of last minute details.”)

print (“This code will never execute.”)

The above code snippet calls the ValueError exception. The except block is executed when the above exception occurs.

 Calling sys.exit command means that the program will exit all blocks designed to handle exceptions.

In this case, the print command within the finally block is executed, but the print command at the end of the program will never be executed.

Note that the block will finally execute under any circumstances. In other words, it doesn’t matter if your program produces an exception.

The commands that fall within the block finally execute in any case,

which is why programmers prefer to place important commands in a block before ending the program.

3. Save the application and select Run Module from the Run menu.

Leave a Reply

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