Back to Python Course

Python Course

In programming, errors are problems that occur during the execution or compilation of a program.

In Python, errors are divided mainly into syntax errors and exceptions.

If errors are not handled properly, they can cause your program to crash.

Types of Errors

  1. Syntax Errors
  • Occur when the Python parser detects incorrect syntax.
  • Prevents the code from running.

For example,

# Missing colon if True print("Hello")

Output

SyntaxError: expected ':'
  1. Runtime Errors (Exceptions)
  • Occur during the execution of a program.
  • Can be handled using exception handling constructs.

For example,

# Division by zero x = 10 / 0

Output

ZeroDivisionError: division by zero

Exception Handling

Python provides a mechanism to handle runtime errors using try-except.

Basic Syntax

try: # risky code except SomeException: # handling code

For example,

try: number = int(input("Enter a number: ")) print(10 / number) except ZeroDivisionError: print("You can't divide by zero!") except ValueError: print("Invalid input. Please enter a number.")

Common Built-in Exceptions

Exception Description ------------------- ---------------------------------------- ZeroDivisionError Raised when dividing by zero ValueError Invalid value passed to a function TypeError Invalid type operation IndexError Accessing invalid index in a list KeyError Accessing a non-existent dictionary key FileNotFoundError File operation fails due to missing file NameError Using a variable that is not defined

Using else and finally

  • else runs if no exception occurs.
  • finally always runs, even if there's an error.

For example,

try: result = 10 / 2 except ZeroDivisionError: print("Error") else: print("No errors occurred!") finally: print("This always runs.")

Raising Exceptions Manually

We can raise your own exceptions using raise.

For example,

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

Custom Exceptions

Define our own exceptions by extending the Exception class.

For example,

class CustomError(Exception): pass def check(value): if value > 100: raise CustomError("Value cannot exceed 100") try: check(150) except CustomError as e: print(f"Caught error: {e}")