2 Replies - 436 Views - Last Post: 15 June 2013 - 06:48 AM Rate Topic: -----

#1 Connectification  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 12
  • Joined: 02-June 13

'try' and 'except'

Posted 13 June 2013 - 07:40 PM

Can anyone tell me what the word 'try', 'except' does?

def get_page(url):
    try:
        if url == "http://xkcd.com/353":
            return '<?xml version="1.0" encoding="utf-8" ?><?xml-stylesheet href="http://imgs.xkcd.com/s/c40a9f8.css" type="text/css" media="screen" ?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" ## I have no idea what this line does, either
        elif url == "http://xkcd.com/554":
            return  '<?xml version="1.0" encoding="utf-8" ?> <?xml-stylesheet href=...
    except:
        return ""
    return "" 



My guess is that they do the same thing as the try-catch block in Java? Is that true?

Is This A Good Question/Topic? 0
  • +

Replies To: 'try' and 'except'

#2 Atli  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 3718
  • View blog
  • Posts: 5,990
  • Joined: 08-June 10

Re: 'try' and 'except'

Posted 13 June 2013 - 07:54 PM

Yea, pretty much. It's the same concept.

You can read all about the Python version of exception handling in the Python manual:
- 8. Errors and Exceptions
Was This Post Helpful? 0
  • +
  • -

#3 chan 06  Icon User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 63
  • Joined: 07-October 12

Re: 'try' and 'except'

Posted 15 June 2013 - 06:48 AM

Try & Except basically means it will run your program even though there is an error. Most common errors include input different variable format on input

ask_number = int(input("Enter a number:"))
print(ask_number)



The user would enter a float or string, which will cause them to have a ValueError error message. This is where the try and except is handy. By re-modifying the code:
ask_number = 0

try:
    ask_number = int(input("Enter a number: "))
    print(ask_number)

except ValueError:
    print("Invalid number.")


If you are using Python 3.x you will note that the first code if you enter float or string, will give you an error message. However the second code, would prompt a message saying "Invalid Number". Hope this gives you a basic idea on how does the try & except works.

This post has been edited by chan 06: 15 June 2013 - 06:49 AM

Was This Post Helpful? 1
  • +
  • -

Page 1 of 1