-5

For what I have understand till now is, computer will try to run the code in try section and will except stuff mentioned in except part. As soon as computer got something as mentioned in except it will run except code.

So, I tried the following:

try:
    if year // 100:
        print year, "is not a leap year"

    else:
        print year, "is not a leap year"


 except year // 400  and year // 4:
        print "is a leap year"

This does not work.

I want to know why it is so?

Freddy
  • 2,216
  • 3
  • 31
  • 34
  • 1
    except only catches expcetions , its not like `if/else` – Anand S Kumar Jul 29 '15 at 06:37
  • you mean it catches the stuff not possible in try section. @AnandSKumar – Freddy Jul 29 '15 at 06:39
  • 2
    You might want to read the [tutorial on `try..except`](https://docs.python.org/3.4/tutorial/errors.html#handling-exceptions). – TigerhawkT3 Jul 29 '15 at 06:39
  • 1
    Unfortunately, your understanding of how try/except works in Python is incorrect. The purpose of try/except is to catch and handle exceptions, which is a specific kind of object that is thrown whenever Python encounters an error. Try/except cannot be used to arbitrarily manipulate control flow, as you are trying to do. – Michael0x2a Jul 29 '15 at 06:40
  • @Michael0x2a Oh okay. I got it. Thank you – Freddy Jul 29 '15 at 06:42

2 Answers2

2

Please, read the doc.

The try statement works as follows.

  • First, the try clause (the statement(s) between the try and except keywords) is executed.
  • If no exception occurs, the except clause is skipped and execution of the try statement is finished.
  • If an exception occurs during execution of the try clause, the rest of the clause is skipped. Then if its type matches the exception named after the except keyword, the except clause is executed, and then execution continues after the try statement.
  • If an exception occurs which does not match the exception named in the except clause, it is passed on to outer try statements; if no handler is found, it is an unhandled exception and execution stops with a message as shown above.
Delgan
  • 18,571
  • 11
  • 90
  • 141
0

basically a try and except is like an if and else...kinda

except that when you try if it doesn't raise an exception it excecutes the try code block but when it fails it'll execute the except block for example

a = [1,2,3,4,"hello"]

for i in a:
    try:
        print(i)
        i + 1

    except:
        print("nope " + i  + " is a string")
Zion
  • 1,570
  • 6
  • 24
  • 36