try except blocks in python

Previous
Next

try-except blocks:

  • Python library is providing pre-defined keywords to handle exception.
  • “try” block is used to place the doubtful code that raises exception.
  • If any exception has risen in the try block, we need to collect the exception object in “except” block to handle.
  • We collect the object reference by specifying Exception(class) type variable.
try :
	->Doubtful code…
	->Related code
except  <Exception_type>  var :
	->Handling logic…

“except” block executes only if there is any exception in try block.

class Demo:
    def main():
        try:
            print("Enter 2 numbers :")
            x = int(input())
            y = int(input())
            z = x+y
            print("Sum :",z)
        except ValueError:
            print("Exception : Invalid input")
        print("End")
        return

Demo.main()
Previous
Next

Add Comment

Courses Enquiry Form