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.

댓글

이 블로그의 인기 게시물

PYTHONPATH, Python 모듈 환경설정

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

git 명령어

[gRPC] server of Java and client of Typescript

[Ubuntu] Apache2.4.x 설치

Create topic on Kafka with partition count, 카프카 토픽 생성하기

리눅스의 부팅과정 (프로세스, 서비스 관리)

Auto-populate a calendar in an MUI (Material-UI) TextField component

The pierce selector in Puppeteer