DelphiLearn PythonPythonPython GUIRAD Studio

Easily Integrate Exception Handling Into Your Python GUI Apps Through Delphi

blogbanner3 5

Illegal operations in Python can raise exceptions. There are plenty of built-in exceptions in Python that are raised when corresponding errors occur.

This post will demonstrate how to run another Python feature in Python4Delphi with RAD Studio: Exception Handling in Python GUI apps and gets the output.

Prerequisites: Before we begin to work, download and install the latest Python for your platform. Follow the Python4Delphi installation instructions mentioned here. Alternatively, you can check out the easy instructions found in this video Getting started with Python4Delphi.

First, open and run our Python GUI using project Demo1 from Python4Delphi with RAD Studio. Then insert the script into the lower Memo, click the Execute button, and get the result in the upper Memo. You can find the Demo1 source on GitHub.

0 rundemo1
Open Demo01dproj

 

1. Python Built-in Exceptions

We can view all the Python built-in exceptions using the built-in local() function as follows:

Output in our Python GUI by Python4Delphi:

1 6268272
All Available Python Built in Exceptions Shown in Python GUI from Python4Delphi

The table below shows built-in exceptions that are usually raised in Python:

ExceptionDescription
ArithmeticErrorRaised when an error occurs in numeric calculations
AssertionErrorRaised when an assert statement fails
AttributeErrorRaised when attribute reference or assignment fails
ExceptionBase class for all exceptions
EOFErrorRaised when the input() method hits an “end of file” condition (EOF)
FloatingPointErrorRaised when a floating point calculation fails
GeneratorExitRaised when a generator is closed (with the close() method)
ImportErrorRaised when an imported module does not exist
IndentationErrorRaised when indendation is not correct
IndexErrorRaised when an index of a sequence does not exist
KeyErrorRaised when a key does not exist in a dictionary
KeyboardInterruptRaised when the user presses Ctrl+c, Ctrl+z or Delete
LookupErrorRaised when errors raised cant be found
MemoryErrorRaised when a program runs out of memory
NameErrorRaised when a variable does not exist
NotImplementedErrorRaised when an abstract method requires an inherited class to override the method
OSErrorRaised when a system related operation causes an error
OverflowErrorRaised when the result of a numeric calculation is too large
ReferenceErrorRaised when a weak reference object does not exist
RuntimeErrorRaised when an error occurs that do not belong to any specific expections
StopIterationRaised when the next() method of an iterator has no further values
SyntaxErrorRaised when a syntax error occurs
TabErrorRaised when indentation consists of tabs or spaces
SystemErrorRaised when a system error occurs
SystemExitRaised when the sys.exit() function is called
TypeErrorRaised when two different types are combined
UnboundLocalErrorRaised when a local variable is referenced before assignment
UnicodeErrorRaised when a unicode problem occurs
UnicodeEncodeErrorRaised when a unicode encoding problem occurs
UnicodeDecodeErrorRaised when a unicode decoding problem occurs
UnicodeTranslateErrorRaised when a unicode translation problem occurs
ValueErrorRaised when there is a wrong value in a specified data type
ZeroDivisionErrorRaised when the second operator in a division is zero
Python Built-in Exceptions.

When these exceptions occur, the Python interpreter stops the current process and passes it to the calling process until it is handled. If not handled, the program will crash (an error message is displayed and our program comes to a sudden unexpected halt).

 

2. Catching Exceptions in Python

In Python, exceptions can be handled using a “try” statement. We placed the critical operation which can raise an exception is inside the “try” clause. The code that handles the exceptions is written in the “except” clause.

The simple example below shows that we can choose what operations to perform once we have caught the exception:

Output in Python GUI:

2 1172487
Catching Exceptions in Python GUI

In this program, we loop through the values of the randomList list. As previously mentioned, the portion that can cause an exception is placed inside the try block.

If no exception occurs, the except block is skipped and normal flow continues(for last value). But if any exception occurs, it is caught by the except block (first and second values).

We use exc_info() function inside sys module to print the name of the exception. We can see that a causes ValueError and 0 causes ZeroDivisionError.

 

3. Catching Specific Exceptions in Python

In the example above, we did not mention any specific exception in the “except” clause.

This is not a good programming practice as it will catch all exceptions and handle every case in the same way. We can specify which exceptions an “except” clause should catch.

A “try” clause can have any number of “except” clauses to handle different exceptions, however, only one will be executed in case an exception occurs.

We can use a tuple of values to specify multiple exceptions in an except clause. Here is an pseudo code example to help you:

 

4. Raising Exceptions in Python

In Python programming, exceptions are raised when errors occur at runtime. We can also manually raise exceptions using the “raise” keyword.

We can optionally pass values to the exception to clarify why that exception was raised. Let’s try these examples to see how they are performing well in the Python4Delphi:

Output:

4 1 7638107
Raising Exceptions in Python Example 1 in Python4Delphi

Output:

4 2 6907656
Raising Exceptions in Python Example 2 in Python4Delphi

Output:

4 3 8041409
Raising Exceptions in Python Example 3 in Python4Delphi

Let’s try to enter -1 as our input, and see the exception arise:

4 4 5814435
Raising Exceptions in Python Example 3 in Python4Delphi

 

5. Python try…else clause

In some situations, we might want to run a certain block of code if the code block inside “try” ran without any errors. For these cases, you can use the optional “else” keyword with the “try” statement.

Note: Exceptions in the else clause are not handled by the preceding except clauses.

Let’s look at an example:

Let’s try to enter 3 (odd number) as our input, and see the exception arise:

5 5254838
Python tryelse clause Example in Python4Delphi

If we pass an even number, the reciprocal is computed and displayed:

5 2 7188612
Python tryelse clause Example 2 in Python4Delphi
 

However, if we pass 0, we get ZeroDivisionError as the code block inside else is not handled by preceding except.

5 3 2884693
Python tryelse clause Example 3 in Python4Delphi

 

6. Python try…finally

The “try” statement in Python can have an optional “finally” clause. This clause is executed no matter what, and is generally used to release external resources.

For example, we may be connected to a remote data center through the network or working with a file or a Graphical User Interface (GUI).

In all these circumstances, we must clean up the resource before the program comes to a halt whether it successfully ran or not. These actions (closing a file, GUI or disconnecting from network) are performed in the finally clause to guarantee the execution.

Here is an example of file operations to illustrate this:

This type of exception handling makes sure that the file is closed even if an exception occurs during the program execution.

Check out Python4Delphi which easily allows you to build Python GUIs for Windows using Delphi.

Related posts
CodeIDELearn PythonPythonPython GUITkinter

How To Make More Than 20 ChatGPT Prompts Work With Python GUI Builders And NumPy Library?

CodeIDEProjectsPythonWindows

Unlock the Power of Python for Deep Learning with Generative Adversarial Networks (GANs) - The Engine behind DALL-E

CodeIDELearn PythonPythonPython GUITkinter

How To Make More Than 20 ChatGPT Prompts Work With Python GUI Builders And Matplotlib Library?

CodeIDELearn PythonPythonPython GUITkinter

How To Make More Than 20 ChatGPT Prompts Work With Python GUI Builders And Pillow Library?

Leave a Reply

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