Try/Except vs. If/Else

Similarities and Differenes?

Page 1 of 1

3 Replies - 11584 Views - Last Post: 21 February 2009 - 12:49 PM Rate Topic: -----

#1 cmwise   User is offline

  • D.I.C Head

Reputation: 5
  • View blog
  • Posts: 169
  • Joined: 14-February 09

Try/Except vs. If/Else

Post icon  Posted 19 February 2009 - 01:31 PM

The exact question is "How is exception-handling using try/except similar to and different from handling exceptional cases using ordinary decisions structures (variations on if)?

I've been looking through my book and can't really find a concrete explanation... I know that with the try/except method, you can have multiple "else"s by using multiple "excepts." I'm just not really sure what the similarities or differences are but I'll keep looking. Thanks for your help :)

Is This A Good Question/Topic? 0
  • +

Replies To: Try/Except vs. If/Else

#2 KevinADC   User is offline

  • D.I.C Regular
  • member icon

Reputation: 27
  • View blog
  • Posts: 401
  • Joined: 23-January 07

Re: Try/Except vs. If/Else

Posted 19 February 2009 - 02:09 PM

Chapter 7.6 summary
Was This Post Helpful? 0
  • +
  • -

#3 Delta62   User is offline

  • D.I.C Head

Reputation: 10
  • View blog
  • Posts: 55
  • Joined: 19-February 09

Re: Try/Except vs. If/Else

Posted 19 February 2009 - 02:35 PM

Try / except is different form if / else because it deals directly with errors encountered in the program. Basically, you use it to catch errors in a program.
So if you had a list:
myList = [1,2,3,4,5]

and you perform an operation that may create an error, such as asking for the value stored at position 6 (which does not exist), you might use a try / except statement to deal with any errors. In this case, maybe something like:

myList = [1,2,3,4,5]
print myList
index = input("Enter the index you would like to see: ")
try:
	print myList[index]
except IndexError:
	print "You have entered an invalid index."

if /else just doesn't deal with errors, specifically.
Was This Post Helpful? 0
  • +
  • -

#4 programble   User is offline

  • (cons :dic :head)

Reputation: 50
  • View blog
  • Posts: 1,315
  • Joined: 21-February 09

Re: Try/Except vs. If/Else

Posted 21 February 2009 - 12:49 PM

Try/Except is useful for catching errors that cannot be predicted, whereas If/Else needs to be a predictable error.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1