python

Error Handling and Exceptions Introduction


Error handling in programming is how you manage errors or unexpected situations that occur while your program is running. In Python, this is done using exceptions. Here’s a simple explanation of error handling in Python:

 

What are Exceptions?

Exceptions are special objects that represent errors or unexpected events in a program. When an error occurs, an exception is "raised" (or thrown). If the program doesn't handle the exception, it will stop and show an error message.

 

Common Exceptions in Python

  • SyntaxError: Raised when there's a syntax error in the code.
  • TypeError: Raised when an operation is performed on an incorrect type.
  • ValueError: Raised when a function receives an argument of the right type but incorrect value.
  • IndexError: Raised when trying to access an index that is out of range.
  • KeyError: Raised when trying to access a dictionary with a key that doesn’t exist.

 

Basic Error Handling

You handle errors in Python using try, except, else, and finally blocks.

 

try and except

The try block lets you test a block of code for errors. The except block lets you handle the error.

try:
   # Code that might cause an error
   x = 10 / 0
except ZeroDivisionError:
   # Code to run if there's a ZeroDivisionError
   print("You can't divide by zero!")

In this example:

  • The code inside the try block (x = 10 / 0) will cause a ZeroDivisionError because you can't divide by zero.
  • The except block catches this error and prints a message instead of stopping the program.

 

else

The else block lets you run code if no errors were raised in the try block.

try:
   x = 10 / 2
except ZeroDivisionError:
   print("You can't divide by zero!")
else:
   print("The division was successful.")

In this example:

  • The code inside the try block (x = 10 / 2) does not cause an error.
  • The else block runs, printing "The division was successful."

 

finally

The finally block lets you run code regardless of the result of the try and except blocks. This is useful for cleaning up resources, such as closing files or releasing network connections.

try:
   x = 10 / 2
except ZeroDivisionError:
   print("You can't divide by zero!")
else:
   print("The division was successful.")
finally:
   print("This will run no matter what.")

In this example:

  • The finally block runs after the try and else blocks, printing "This will run no matter what."

 

Custom Exceptions

You can create your own exceptions by defining a new class that inherits from the built-in Exception class.

class MyCustomError(Exception):
   pass
try:
   raise MyCustomError("Something went wrong!")
except MyCustomError as e:
   print(e)

In this example:

  • MyCustomError is a custom exception.
  • raise MyCustomError("Something went wrong!") raises the custom exception.
  • The except block catches the custom exception and prints the error message.

 


python