# Errors, real quick Author: Paulo Queiroz Language: en Source: https://raggesilver.com/blog/05-errors-real-quick Let's take a look at raising and handling errors. In this post, we will take a quick look at raising and handling errors. We'll use Python in the examples, but the same concept exists in various languages. ## What is an error? This might seem like a silly question, but in programming, an error might not be the same thing as the conversational meaning of the word. If you've ever written code like this, you could have raised an error: ```py a = int(input("Enter a number: ")) b = int(input("Enter another number: ")) if b == 0: print("You can't divide by zero!") else: print(f"{a} / {b} = {a / b}") ``` In this example, we are checking if the second number is zero before dividing, but instead of raising an error, we are printing a message. This is a common practice, but it's not the only way to handle errors. ## Raising an error In Python, you can raise an error using the `raise` keyword. Here's an example: ```py def divide(a, b): if b == 0: raise ValueError("You can't divide by zero!") return a / b a = int(input("Enter a number: ")) b = int(input("Enter another number: ")) divide(a, b) ``` In this example, if the user inputs zero as the second number, the function will raise an error. This will stop the program where it is, print an error, and exit. Nothing after the line where the error was raised will ever be executed. ## Handling an error We don't have to let the program crash when any error is raised. In fact, we should almost always handle errors. Here's how we can do that: ```py def divide(a, b): if b == 0: raise ValueError("You can't divide by zero!") return a / b a = int(input("Enter a number: ")) b = int(input("Enter another number: ")) try: result = divide(a, b) print(f"{a} / {b} = {result}") except ValueError as e: print("An error occurred:", e) ``` In this example the program will not crash. Instead, after the error is raised, the return statement (or anything that could have come after the line where the error was raised) will not be executed. The program will jump to the `except` block and execute the code there. > This example is silly, as Python will already raise an error if you try to > divide by zero. But it serves to illustrate the concept. ## Conclusion Errors are a concept present in various languages. They are a way to stop the execution of a program when something unexpected happens. We can raise errors ourselves, or we can let the language raise them for us. We can also handle errors, so the program doesn't crash when they happen. In the next post we will take a look at why some people say that exceptions are a bad concept and what the alternatives are.