throw and catch errors in python

In Python, you can throw exceptions and catch them using try-except blocks.

To throw an exception, you can use the "raise" keyword followed by an exception type and an error message:

main.py
raise ValueError("Invalid input")
34 chars
2 lines

To catch an exception, you can use a try-except block. Here's an example:

main.py
try:
    num = int(input("Enter a number: "))
except ValueError:
    print("Invalid input. Please enter a valid integer.")
123 chars
5 lines

In this example, if the user enters a non-integer input, the ValueError exception will be thrown and caught by the except block, which will print an error message.

You can also define your own custom exception types by creating a new class that inherits from the built-in "Exception" class:

main.py
class MyCustomError(Exception):
    pass  # you can add custom behavior here
77 chars
3 lines

And then you can throw and catch instances of your custom exception type:

main.py
try:
    if some_condition:
        raise MyCustomError("Some error message")
except MyCustomError as e:
    print(f"An error occurred: {e}")
142 chars
6 lines

gistlibby LogSnag