🚧Summaries For Lessons 24+ Are Still Work In Progress!

“Whoever is patient has great understanding…" Proverbs 14:29

Error Handling Basics (try/except)

Description here...

Error Handling Basics (try/except)

Description here...

Error Handling Basics (try/except)

Description here...

- Understand Errors in Python
- Error Handling with try/except statements
- How to suppress Errors

📃Error Handling In Python:

It's very common to get errors in Python, especially during development. Until now I just told you to ignore them and that's not the best advice... So let's look into Error Handling.

Firstly, we need a simple error so we can look into it. Let's break a math law and try to divide a number by 0.

print(1 / 0)
print(1 / 0)
print(1 / 0)

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

🔹File Name
🔹Code Line with Error
🔹Python code
🔹Error Type with Description (ZeroDivisionError in this case)

Usually, you would only need to look at the line number and the error message itself. Usually, that's enough to understand what has happened.

At first some error messages are going to be confusing, but once you solve them a few times it will come as a second nature. If confused - Ask Chat GPT about the error messages, it will break it down into human dialect.

Basic Error Handling with Try-Except

To handle errors in Python we need to use try/except statements.

try:
    print(1 / 0)
    print('Hello')
except:
    pass

print('The End.')
try:
    print(1 / 0)
    print('Hello')
except:
    pass

print('The End.')
try:
    print(1 / 0)
    print('Hello')
except:
    pass

print('The End.')

Here's what's going to happen...

Python will start executing trycode block. If there are no errors, then it will finish try-block and ignore whatever is in except-block.

❌ However, if you get an error inside of try block, instead of crashing your script, it will suppress it and execute whatever you wrote in except block. In this case pass means do nothing, so we will only suppress an error.

💡It's okay to suppress errors in development, but it should be avoided in production.

The general rule is - if you have a piece of code that might encounter errors, then it's good idea to introduce an error handling. It can be as simple as catch and report.

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.')
try:
    print(1 / 0)
    print('No Error.')
except:
    print("*** Error has happened! *** 😱")

print('Hello World.')
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.

Sign-Up For Future Updates✨

Be among the first people to hear about
New Python Courses or Useful Resources!

Once there's enough demand I might start a Python Newsletter
with even more Tips and Tricks to help you learn it better!


Want To Donate? Click here.

Sign-Up For Future Updates✨

Be among the first people to hear about
New Python Courses or Useful Resources!

Once there's enough demand I might start a Python Newsletter
with even more Tips and Tricks to help you learn it better!


Want To Donate? Click here.

Sign-Up For Future Updates✨

Be among the first people to hear about
New Python Courses or Useful Resources!

Once there's enough demand I might start a Python Newsletter
with even more Tips and Tricks to help you learn it better!


Want To Donate? Click here.

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.")
try:
    print(1 / 0)
except ZeroDivisionError:
    print("Division by zero is not allowed.")
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')
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')
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)
try:
    print(1 / 0)
except Exception as e:
    print(e)
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())
import traceback

try:
    print(1 / 0)
except:
    print(traceback.format_exc())
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.

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.

Happy Coding!

🙋‍♂️ See you in the next lesson.
- EF

Happy Coding!

🙋‍♂️ See you in the next lesson.
- EF

Happy Coding!

🙋‍♂️ See you in the next lesson.
- EF

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!

⌨️ Happy Coding!

⌨️ Happy Coding!

If you have any questions, leave them in the YouTube Comments.

If you have any questions, leave them in the YouTube Comments.

If you have any questions, leave them in the YouTube Comments.

Should I always use Try/Except?

Should I always use Try/Except?

Should I always use Try/Except?

Have a Question?

Have a Question?

Have a Question?

Sign-Up For Future Updates✨

Be among the first people to hear about
New Python Courses or Useful Resources!

Once there's enough demand I might start a Python Newsletter
with even more Tips and Tricks to help you learn it better!


Want To Donate? Click here.

Sign-Up For Future Updates✨

Be among the first people to hear about
New Python Courses or Useful Resources!

Once there's enough demand I might start a Python Newsletter
with even more Tips and Tricks to help you learn it better!


Want To Donate? Click here.

Sign-Up For Future Updates✨

Be among the first people to hear about
New Python Courses or Useful Resources!

Once there's enough demand I might start a Python Newsletter
with even more Tips and Tricks to help you learn it better!


Want To Donate? Click here.

PS. Python can change your career and how you think about problems.
Be Careful 🙂

PS. Python can change your career and how you think about problems.
Be Careful 🙂

PS. Python can change your career and how you think about problems.
Be Careful 🙂

Sposored by LearnRevitAPI.com