Posts

Showing posts with the label Throwing and Creating Custom exceptions

Python - Throwing and Creating Custom exceptions

Image
Python Raise an Exception Sometimes you may need to raise an exception manually. The raise operator can be used to do this. For instance, let’s raise an exception: try :     number1 = int(input( "Enter the first number: " ))     number2 = int(input( "Enter the second number: " ))     if number2 == 0 :         raise Exception( "The second number must not be 0" )     print( "Result of dividing two numbers:" , number1/number2) except ValueError:     print( "Invalid data entered" ) except Exception as e:     print(e) print( "End program" ) In the raise statement, a BaseException is passed to the statement. In this case, an Exception object is passed to the raise statement. Then, a message is passed to the constructor for this type of object. Then, the user can see the message in the raise statement. If number2 equals 0, then raise statement works. Then, raise statement generates an exception. Then, program control passes to e