Python-11

/

/

/

python/11-error-handling

Handle Errors with Try/Except

During this course, we’ve encountered a few errors, and so far, I’ve told you to just ignore and avoid them. That’s not the best advice, but it worked until now. However, now it’s time to properly introduce you to the basics of error handling in Python.

Python-11

/

/

/

python/11-error-handling

Handle Errors with Try/Except

During this course, we’ve encountered a few errors, and so far, I’ve told you to just ignore and avoid them. That’s not the best advice, but it worked until now. However, now it’s time to properly introduce you to the basics of error handling in Python.

Lesson Objectives

  • Error Handling Basics

  • How to supress errors

  • How to handle multiple errors

Are you Ready?

Summary

Understanding Errors in Python

Firstly, let's create a simple error in python and look into it.

We are about to break some math laws and divide a number by 0.

print(1 / 0)

When an error occurs, you’ll see a traceback message of the last call that includes:

  • File where it happened

  • Code Line where it occurred

  • Line with Python code

  • Error type with Description (ZeroDivisionError in this case)

Usually, you would only need to look at the line number where error occurred and the error message itself. And then you will be able to find what happened.


Also, I want to point your attention to the table of all built-in error types. This can be useful if you want to create solution for specific errors only. But in general, you should only focus on Exception itself, because it's a base class for all Exceptions in python.

Basic Error Handling with Try-Except

Whenever you have a piece of code that might encounter errors, you should introduce an error handling. And it's not so complicated in python.

We need to use try/except statement, that will try to execute your code block, and if any error happens (or specified one), then you will execute the error handling code block.

Here is the basic Syntax:

try:
    print(1 / 0)
    print('No Error.')
except:
    pass

print('Hello World.')

Here’s what happens:

  • The try block contains the code that might cause an error.

  • The except block is executed only if an error occurs.

  • In this case, passsimply means “do nothing.”

So, when we run this code, we won't see any error messages and the program will continue running and we will see 'Hello World' statement. But, keep in mind that 'No Error' will not be executed, because an error happened before that, so the code block won't be executed after encountering an error. It stops right there and looks into except block.


We could also write something in the except to be more descriptive.

try:
    print(1 / 0)
    print('No Error.')
except:
    print("*** Error has happened! *** 😱")

print('Hello World.')

This time we will see messages `'Error has happened' and 'Hello World', because we had an error in the try block, so it triggered the except part.


💡 This is the standard error handling in python, especially for beginners.

Handling Specific Errors

Let's look a little deeper into error handling. It might be more advanced, but sometimes you want to be more specific with handling your errors.

You can specify multiple except blocks for different kind of error. But to be honest, that is more relevant on bigger scale development, so 99% of you won't use it. But it's good to know.

So, if you would want handle ZeroDivisonError specifically, you would write like this:

try:
    print(1 / 0)
except ZeroDivisionError:
    print("Division by zero is not allowed.")

If a ZeroDivisionError occurs, this will print a more useful message instead of a generic error message. Otherwise you will get an error in the console, because it won't be handeled.

Catching Multiple Errors

You can also catch multiple errors at once like this:

try:
    print(1 / 0)
    x = x
except ZeroDivisionError:
    print("Division by zero is not allowed.")
except NameError:
    print("Fix your syntax!")
except:
    print('Something else happened')
Getting the Error Message

While we should avoid all errors in the final tool, errors are very important during development. So, make sure you don't supress all your error messages too early, and then wonder why nothing works.

You could avoid using try/except blocks until later, or you could actually print the error message without crashing you code.

If you want to get a very simple and brief description, you could use syntax like this:

try:
    print(1 / 0)
except Exception as e:
    print(e)

This prints the actual error message (division by zero), which can be helpful for debugging.

But I would recommend you to use traceback package, to get more descriptive error message, exactly how you see it in the console.

So you would write something like this:

import traceback

try:
    print(1 / 0)
except:
    print(traceback.format_exc())

This prints the full traceback, including the file, line number, and exact error message, which is useful for debugging.

Practical Application of Try-Except

Let's consider a real-world example in Revit API, where error handling can be used to our advantage.

Imagine that we are renaming a lot of views in Revit and we won't to avoid getting "View Name already exists" error. We could create a list of all view names in the project and then check inside if name is unique or not.

But it would be much better to use try/except block. We can create a loop and then try to rename a view. If we succeed, then we break out of the loop and continue script execution. However, if we get an error, we can provide a solution to unique problem, and we can keep adding some '*' symbol in the end until it's unique.

Here is a code sample without going into too much detail.

new_name = 'EF_ViewPlan'

# Rename View (Loop x10, adding '*' until the view name is unique)
for i in range(10):
    try:
        view.Name = new_name
        break  # Stop the loop if the renaming is successful
    except:
        new_name += '*'  # Append '*' to the name if an exception occurs

Summary

In general, error handling is a very important part of writing robust python code. You should always think about how you could break your script, so you can come up with an error handling before it even happened.

HomeWork

Open code editor and create a few errors, and try to handle these errors yourself by using simple try/except statements.

It will also help you to use a lot of print statements before, after and especially inside of your try/except blocks. This will help you understand how it is being executed so you can prepare for it in the future.

Experiment with errors and don't be afraid of them. They just tell you that you did something wrong, nothing more than that.

⌨️ Happy Coding!

Questions:

Should I always use try/except?

Should I always use try/except?

Discuss the lesson :

P.S. Sometimes this chat might experience connection issues.

Use Discord App for best experience.

Discuss the lesson :

P.S. Sometimes this chat might experience connection issues.

Use Discord App for best experience.

Discuss the lesson :

P.S. Sometimes this chat might experience connection issues.

Use Discord App for best experience.

Unlock Community

The pyRevit Hackers Community is only available with pyRevit Hackers Bundle.
Upgrade Here to Get Access to the community and all pyRevit Courses.

Use coupon code "upgrade" to get 150EUR Discount as a member.

⌨️ Happy Coding!

Unlock Community

The pyRevit Hackers Community is only available with pyRevit Hackers Bundle.
Upgrade Here to Get Access to the community and all pyRevit Courses.

Use coupon code "upgrade" to get 150EUR Discount as a member.

⌨️ Happy Coding!

Unlock Community

The pyRevit Hackers Community is only available with pyRevit Hackers Bundle.
Upgrade Here to Get Access to the community and all pyRevit Courses.

Use coupon code "upgrade" to get 150EUR Discount as a member.

⌨️ Happy Coding!

© 2023-2024 EF Learn Revit API

© 2023-2024 EF Learn Revit API

© 2023-2024 EF Learn Revit API