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.

댓글

이 블로그의 인기 게시물

Using the MinIO API via curl

How to split a list into chunks of 100 items in JavaScript, 자바스크립트 리스트 쪼개기

HTML Inline divisions at one row by Tailwind

Boilerplate for typescript server programing

가속도 & 속도

Gradle multi-module project

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

CDPEvents in puppeteer

Sparse encoder

Reactjs datetime range picker