Use app×
Join Bloom Tuition
One on One Online Tuition
JEE MAIN 2025 Foundation Course
NEET 2025 Foundation Course
CLASS 12 FOUNDATION COURSE
CLASS 10 FOUNDATION COURSE
CLASS 9 FOUNDATION COURSE
CLASS 8 FOUNDATION COURSE
0 votes
94 views
in Python by (117k points)
Can you raise your own exceptions in try-except blocks?

Please log in or register to answer this question.

1 Answer

0 votes
by (117k points)

Yes, you can raise your own exceptions in try-except blocks using the raise statement. This can be useful when you want to handle a specific error condition in your code.

Here's an example:

def divide(a, b):
    try:
        if b == 0:
            raise ValueError("Cannot divide by zero")
        result = a / b
        return result
    except ValueError as e:
        print(e)

print(divide(10, 2)) # Output: 5.0
print(divide(10, 0)) # Output: Cannot divide by zero
 

In this example, we have defined a divide() function that takes two arguments, a and b. Inside the try block, we check if b is equal to zero. If it is, we raise a ValueError with the message "Cannot divide by zero". If there are no exceptions, we calculate the result and return it.

In the except block, we catch the ValueError exception and print the error message to the console. When we call divide() with b set to zero, the function raises the ValueError exception and prints the error message, "Cannot divide by zero". When we call divide() with a non-zero value for b, the function returns the correct result.

Related questions

0 votes
1 answer
asked Mar 29, 2023 in Python by kvdevika (117k points)
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Welcome to Sarthaks eConnect: A unique platform where students can interact with teachers/experts/students to get solutions to their queries. Students (upto class 10+2) preparing for All Government Exams, CBSE Board Exam, ICSE Board Exam, State Board Exam, JEE (Mains+Advance) and NEET can ask questions from any subject and get quick answers by subject teachers/ experts/mentors/students.

Categories

...