Exception in python

In Python, exceptions can be caught using the try-except block. This allows you to handle errors gracefully without interrupting the flow of the program. Here's how you can do it:


Basic Syntax

try:
    # Code that might raise an exception
    risky_code()
except SomeException:
    # Code to handle the exception
    print("An exception occurred!")

Catching Specific Exceptions

You can specify the type of exception you want to catch. This ensures that only certain exceptions are caught, and others are allowed to propagate.

try:
    x = 1 / 0  # This will raise a ZeroDivisionError
except ZeroDivisionError:
    print("Cannot divide by zero!")

Catching Multiple Exceptions

If you want to catch multiple types of exceptions, you can either use multiple except clauses or handle them in a tuple.

try:
    x = int("invalid")  # This will raise a ValueError
except (ValueError, TypeError) as e:
    print(f"An exception occurred: {e}")

Using else and finally

  • else: The code inside the else block will run only if no exception occurs.
  • finally: The code inside the finally block will always run, regardless of whether an exception occurred or not.
try:
    x = 10 / 2
except ZeroDivisionError:
    print("Division by zero error!")
else:
    print("Division successful!")
finally:
    print("This block always runs.")

Output:

Division successful!
This block always runs.

Catching All Exceptions (Exception)

You can use a generic except block to catch any kind of exception, though it's generally not recommended unless you're sure you need to handle all exceptions.

try:
    x = 1 / 0
except Exception as e:
    print(f"An error occurred: {e}")

Raising an Exception Manually

You can also raise exceptions yourself using the raise keyword.

x = -5
if x < 0:
    raise ValueError("x cannot be negative!")

Summary

  • Use try-except to catch exceptions.
  • Catch specific exceptions where possible.
  • Use else for code that should run if no exception occurs.
  • Use finally for code that should run no matter what happens.
  • Avoid catching all exceptions with except Exception unless necessary.

This approach will help you manage errors gracefully while keeping your code clean and understandable.

댓글

이 블로그의 인기 게시물

Install and run an FTP server using Docker

Using the MinIO API via curl

PYTHONPATH, Python 모듈 환경설정

Elasticsearch Ingest API

오늘의 문장2

How to checkout branch of remote git, 깃 리모트 브랜치 체크아웃

Fundamentals of English Grammar #1

To switch to a specific tag in a Git repository

You can use Sublime Text from the command line by utilizing the subl command

티베트-버마어파 와 한어파(중국어파)의 어순 비교