Каковы обычно используемые исключения на этапе выполнения в Java? [закрытый]

Это выполнимо:

Ваш TextBlock TextAlignment свойство должно быть установлено на Center:

<TextBlock Name="textBlock1" TextAlignment="Center" Text="Stacked!" />

Тогда добавляют NewLine с между каждым символом:

textBlock1.Text =
    String.Join(
        Environment.NewLine,
        textBlock1.Text.Select(c => new String(c, 1)).ToArray());

(Использование System.Linq для создания массива строк из отдельных символов в исходной строке. Я уверен, что существуют другие способы сделать это...)

45
задан Winston Chen 1 October 2009 в 09:19
поделиться

4 ответа

Я никогда не выбрасываю NullPointerException . Для меня это тот, который естественным образом появляется в коде, когда что-то идет не так, и требует от разработчика посмотреть, что происходит. Затем он устраняет причину, и это больше не повторится.

Я использую IllegalStateException , чтобы сигнализировать, что объект неправильно настроен или что вызовы идут в неправильном порядке. Однако все мы знаем, что в идеале объект должен гарантировать, что он не может находиться в плохом состоянии и что вы не можете вызывать его в неправильном порядке (создайте конструктор и получившийся объект ...).

Я использую много IllegalArgumentException , когда метод обнаруживает, что его параметры неверны. Любой общедоступный метод отвечает за остановку обработки (чтобы избежать косвенных ошибок, которые труднее понять). Кроме того, несколько if в начале метода служат цели документации (документация, которая никогда не отклоняется от кода, потому что это код :-)).

     public void myMethod(String message, Long id) {
       if (message == null) {
          throw new IllegalArgumentException("myMethod's message can't be null");
          // The message doesn't log the argument because we know its value, it is null.
       }
       if (id == null) {
          throw new IllegalArgumentException("myMethod's id can't be null");
          // This case is separated from the previous one for two reasons :
          // 1. to output a precise message
          // 2. to document clearly in the code the requirements
       }
       if (message.length()<12) {
          throw new IllegalArgumentException("myMethod's message is too small, was '" + message + "'");
          // here, we need to output the message itself, 
          // because it is a useful debug information.
       }
     }

Я также использую специальные исключения времени выполнения , чтобы сигнализировать об исключительных условиях более высокого уровня.

Например, если модуль моего приложения не может запуститься, у меня может возникнуть исключение ModuleNotOperationalException (в идеале с помощью универсального кода, такого как перехватчик, в противном случае - с помощью определенного кода), когда его вызывает другой модуль . После этого архитектурного решения каждый модуль должен иметь дело с этим исключением в операциях, вызывающих другие модули ...

68
ответ дан 26 November 2019 в 21:11
поделиться

I've always considered that runtime exceptions should represent programming errors (e.g. null reference passed in when not expected, array index out of bounds, etc.) while checked exceptions should represent exceptional conditions in the environment that cannot be "coded away" (e.g. IOException, SQLException).

One violation of this is that sometimes you'll need to wrap what ought to be a checked exception in a RuntimeException, in order to satisfy the definition of an interface. As a brief example, you might have some snazzy implementation of java.util.List that manages a distributed list between multiple machines. Clearly this would throw checked exceptions (probably some subclass of IOException) if defined on its own, but the benefits of making this class implement List is that clients can use it almost transparently, anywhere they use another list.

This can lead to what Joel terms a leaky abstraction, though, so it's important that your documentation is clear what exceptions can be thrown and what they mean! In this case I find a custom subclass of RuntimeException to generally be clearer at communicating the root cause rather than trying to shoehorn it into an existing runtime exception class.

12
ответ дан 26 November 2019 в 21:11
поделиться

UnknownException, очень полезно: P

Мне также нравится org.apache.commons. lang.NotImplementedException

3
ответ дан 26 November 2019 в 21:11
поделиться

I use IllegalArgumentException relatively often. Most of the time, I will try to return the default value as soon as it is logical but some of the time it was not, and so I use this one.

Another one I use is ArrayIndexOutOfBoundsException.

3
ответ дан 26 November 2019 в 21:11
поделиться
Другие вопросы по тегам:

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