搜尋此網誌

2026年11月10日星期二

Handling Exceptions in Python

In Python, try/except is used for exception handling. It allows your program to continue running when an error occurs instead of crashing.

try:
    result = 10 / 0
except:
    print("An error occurred")

The finally block contains code that always executes, whether an exception occurs or not.

start = time.time()
This line records the current time and stores it in the variable start.
Before using it, you need to import the time module.

time.sleep(0.5)
This statement tells Python to pause (sleep) for 0.5 seconds before continuing to the next line of code.

print(f'Function took {time.time() - start} seconds to execute')
This line uses an f-string (formatted string literal) to display how long a function or block of code took to run.

Catching an exception means handling an error so that your program doesn't crash.
try:
    1 / 0
except ZeroDivisionError:
    print("You cannot divide by zero")

Custom Decorators in Python
A decorator is a function that takes another function, adds some behavior to it, and returns the modified function.

def my_decorator(func):
    def wrapper():
        print("Before function call")
        func()
        print("After function call")
    return wrapper

@my_decorator
def greet():
    print("Hello!")
greet()

Output:
Before function call
Hello!
After function call

An argument is a value you pass to a function when calling it.
print("Hello")
"Hello" is an argument passed to the print() function.

def catch_errors(func):
    def wrapper(*args):
        try:
            return func(*args)
        except Exception as e:
            print(f"Error: {e}")
    return wrapper

And a function that raises an exception:
@catch_errors
def divide(a, b):
    if b == 0:
        raise ValueError("Cannot divide by zero")

    return a / b


divide(10, 0)
      │
      ▼
wrapper(10, 0)
      │
      ▼
func(*args)
      │
      ▼
divide(10, 0)
      │
      ▼
raise ValueError
      │
      ▼
except Exception as e
      │
      ▼
print error message

Microsoft Copilot

沒有留言:

發佈留言