Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Exception handling


Published on

Exception handling

  • Be the first to comment

  • Be the first to like this

Exception handling

  1. 1. Disclaimer: This presentation is prepared by trainees ofbaabtra as a part of mentoring program. This is not officialdocument of baabtra –Mentoring PartnerBaabtra-Mentoring Partner is the mentoring division of baabte System Technologies Pvt .Ltd
  2. 2. Title of the presentation Reshmi R ramaswami r +917736719717
  3. 3. Handling Exceptions• Exception: An error that occurs during the execution of a program• Exception is raised and can be caught (or trapped) then handled• Unhandled, an exception halts the program and an error message is displayed>>> 1/0Traceback (most recent call last): File "<pyshell#0>", line 1, in -toplevel- 1/0ZeroDivisionError: integer division or modulo by zero
  4. 4. Try/Except try: num = float(raw_input("Enter a number: "))except: print "Something went wrong!"• ‘try’ statement sections of code that could raise exception• If an exception is raised, then the ‘except’ block is run• If no exception is raised, then the ‘except’ block is skipped
  5. 5. Try/Finally• In try/finally, finally block is always run whether an exception occurs or not try: <block of statements>finally: <block of statements>• Ensure some actions to be done in any case• It can not be used in the try with except and else.
  6. 6. Specifying an Exception Type try: num = float(raw_input("nEnter a number: "))except(ValueError): print "That was not a number!“• Different types of errors raise different types of exceptions• except clause can specify exception types to handle• Attempt to convert "Hi!" to float raises ValueError exception• Avoid general, catch-all exception handling• Specify exception types to handle each individual case
  7. 7. Handling Multiple Exception Types (contd…) for value in (None, "Hi!"): try: print "Attempting to convert", value, "–>", print float(value) except(TypeError): print "Can only convert string or number!" except(ValueError): print "Can only convert a string of digits!“• Each except clause can offer specific code for each individual exception type
  8. 8. Try/Else try: num = float(raw_input("nEnter a number: "))except(ValueError): print "That was not a number!"else: print "You entered the number", num• Can add single else clause after all except clauses• else block executes only if no exception is raised• num printed only if assignment statement in the try block raises no exception
  9. 9. If this presentation helped you, please visit our page and like it. Thanks in | |
  10. 10. Contact Us