Blog 8: Error Handling and Debugging

Error Handling and Debugging in Python

Errors are a natural part of programming, especially in hacking scripts where inputs and systems can be unpredictable. Learning how to handle exceptions and debug your Python code effectively will save you hours of frustration and help you build more reliable tools.

1. What are Exceptions?

Exceptions are errors detected during execution. Instead of crashing your program, Python allows you to handle them using try, except, else, and finally.

try:
    x = 10 / 0
    except ZeroDivisionError:
    print("You can't divide by zero!")

2. Handling Multiple Exceptions

try:
    value = int(input("Enter a number: "))
    result = 10 / value
    except ValueError:
    print("That's not a valid number!")
    except ZeroDivisionError:
    print("Cannot divide by zero!")

3. Using else and finally

try:
    print("Trying...")
    x = 10 / 2
    except:
        print("Error occurred")
    else:
        print("Success!")
    finally:
        print("This always runs.")

4. Raising Your Own Exceptions

age = -5

if age < 0:
    raise ValueError("Age cannot be negative")

5. Basic Debugging with print()

Start by printing values step-by-step. While not ideal for big projects, it's quick and often effective in scripts:


def divide(a, b):
    print("a =", a)
    print("b =", b)
    return a / b
print(divide(10, 2))

pdb is Python's built-in debugger that lets you step through your code line-by-line.

import pdb
    
x = 10
y = 0
pdb.set\_trace()
result = x / y

Use commands like n (next), c (continue), q (quit), and p variable (print value).


7. Logging Instead of Printing

Use the logging module to track your script's activity:

import logging
logging.basicConfig(level=logging.INFO)
logging.info("Script started")

Conclusion

Mastering exception handling and debugging is critical for anyone writing hacking tools, automation scripts, or any serious Python code. These tools help you write clean, stable, and robust code.

If you found this post helpful, share it with your friends. Happy coding!

Comments