Попробуй еще Python

Вы можете попробовать использовать jquery.pep.js:

jquery.pep.js - это легкий плагин jQuery, который превращает любой элемент DOM в объект перетаскивания. Он работает в основном во всех браузерах, от старого до нового, от касания до щелчка. Я построил его, чтобы удовлетворить потребность, в которой перетаскиваемый интерфейс jQuery UI не выполнялся, поскольку он не работал на сенсорных устройствах (без хакерства).

Веб-сайт , Ссылка GitHub

499
задан Honest Abe 21 February 2014 в 07:08
поделиться

9 ответов

The statements in the else block are executed if execution falls off the bottom of the try - if there was no exception. Honestly, I've never found a need.

However, Handling Exceptions notes:

The use of the else clause is better than adding additional code to the try clause because it avoids accidentally catching an exception that wasn’t raised by the code being protected by оператор try ... except.

Итак, если у вас есть метод, который может, например, выдавать IOError , и вы хотите перехватывать исключения, которые он вызывает, но есть еще кое-что, что вы хотите сделать, если первая операция завершилась успешно, и вы не хотите поймать IOError в результате этой операции, вы можете написать что-то вроде этого:

try:
    operation_that_can_throw_ioerror()
except IOError:
    handle_the_exception_somehow()
else:
    # we don't want to catch the IOError if it's raised
    another_operation_that_can_throw_ioerror()
finally:
    something_we_always_need_to_do()

Если вы просто поместите another_operation_that_can_throw_ioerror () после operation_that_can_throw_ioerror , за исключением перехватит ошибки второго вызова. И если вы поместите его после всего блока try , он будет запускаться всегда, и только после finally . else позволяет убедиться, что

  1. вторая операция выполняется только в том случае, если нет исключения,
  2. it ' s запускаются перед блоком finally , и
  3. любые IOError s, которые он вызывает, здесь не обнаруживаются
797
ответ дан 22 November 2019 в 22:24
поделиться

The else: block is confusing and (nearly) useless. It's also part of the for and while statements.

Actually, even on an if-statement, the else: can be abused in truly terrible ways creating bugs that are very hard to find.

Consider this.

   if a < 10:
       # condition stated explicitly
   elif a > 10 and b < 10:
       # condition confusing but at least explicit
   else:
       # Exactly what is true here?
       # Can be hard to reason out what condition is true

Think twice about else:. It is generally a problem. Avoid it except in an if-statement and even then consider documenting the else- condition to make it explicit.

-16
ответ дан 22 November 2019 в 22:24
поделиться

Блок else часто может существовать для дополнения функциональности, которая встречается в каждом , кроме блока .

try:
    test_consistency(valuable_data)
except Except1:
    inconsistency_type = 1
except Except2:
    inconsistency_type = 2
except:
    # Something else is wrong
    raise
else:
    inconsistency_type = 0

"""
Process each individual inconsistency down here instead of
inside the except blocks. Use 0 to mean no inconsistency.
"""

В этом случае inconsistency_type устанавливается в каждом блоке except, так что поведение дополняется в случае отсутствия ошибок в else .

Конечно, я описываю это как шаблон, который может проявиться в вашем собственном код когда-нибудь. В этом конкретном случае вы просто устанавливаете inconsistency_type равным 0 перед блоком try в любом случае.

1
ответ дан 22 November 2019 в 22:24
поделиться

Вот и все. Блок else в предложении try-except существует для кода, который выполняется, когда (и только когда) выполненная операция завершается успешно. Его можно использовать, и можно злоупотреблять.

try:
    fp= open("configuration_file", "rb")
except EnvironmentError:
    confdata= '' # it's ok if the file can't be opened
else:
    confdata= fp.read()
    fp.close()

# your code continues here
# working with (possibly empty) confdata

Лично мне это нравится, и я использую его, когда это необходимо. Он семантически группирует операторы.

3
ответ дан 22 November 2019 в 22:24
поделиться

Looking at Python reference it seems that else is executed after try when there's no exception. The optional else clause is executed if and when control flows off the end of the try clause. 2 Exceptions in the else clause are not handled by the preceding except clauses.

Dive into python has an example where, if I understand correctly, in try block they try to import a module, when that fails you get exception and bind default but when it works you have an option to go into else block and bind what is required (see link for the example and explanation).

If you tried to do work in catch block it might throw another exception - I guess that's where the else block comes handy.

5
ответ дан 22 November 2019 в 22:24
поделиться

Even though you can't think of a use of it right now, you can bet there has to be a use for it. Here is an unimaginative sample:

With else:

a = [1,2,3]
try:
    something = a[2]
except:
    print "out of bounds"
else:
    print something

Without else:

try:
    something = a[2]
except:
    print "out of bounds"

if "something" in locals():
    print something

Here you have the variable something defined if no error is thrown. You can remove this outside the try block, but then it requires some messy detection if a variable is defined.

9
ответ дан 22 November 2019 в 22:24
поделиться

I find it really useful when you've got cleanup to do that has to be done even if there's an exception:

try:
    data = something_that_can_go_wrong()
except Exception as e: # yes, I know that's a bad way to do it...
    handle_exception(e)
else:
    do_stuff(data)
finally:
    clean_up()
16
ответ дан 22 November 2019 в 22:24
поделиться

One use: test some code that should raise an exception.

try:
    this_should_raise_TypeError()
except TypeError:
    pass
except:
    assert False, "Raised the wrong exception type"
else:
    assert False, "Didn't raise any exception"

(This code should be abstracted into a more generic test in practice.)

47
ответ дан 22 November 2019 в 22:24
поделиться

В PEP 380 есть хороший пример try-else . По сути, все сводится к разной обработке исключений в разных частях алгоритма.

Это примерно так:

try:
    do_init_stuff()
except:
    handle_init_suff_execption()
else:
    try:
        do_middle_stuff()
    except:
        handle_middle_stuff_exception()

Это позволяет вам написать код обработки исключений ближе к месту возникновения исключения.

6
ответ дан 22 November 2019 в 22:24
поделиться
Другие вопросы по тегам:

Похожие вопросы: