U
U
UltimateOrb2016-03-16 13:13:34
Java
UltimateOrb, 2016-03-16 13:13:34

Is it considered good practice to throw exceptions in Java?

There is a function that processes the barcodes of the boxes. During its execution, many different checks take place, for example: whether the box has already been scanned, whether the box is in stock, etc. If any of the checks suddenly fails, you need to throw out an error message. The question is how to properly throw out such messages. There are two options (example code):
1. Through exceptions

// callback от сканера
public void callbackScaner(String data) {
  try {
     scanBarcode(String barcode);
   } catch (Exeprion e) {
      showMsg(e.getMessage());
   }
}

// обработка бар-кода
public void scanBarcode(String barcode) throws Exception {
   Box box= getProd(barcode);
   if (box== null) throw new Exeption("Коробки нет на складе");
   if (box.ready) throw new Exeption("Коробка уже отсканирована");
   ...   
}

2. Through verification
// callback от сканера
public void callbackScaner(String data) {
     scanBarcode(String barcode);
}

// обработка бар-кода
public void scanBarcode(String barcode) throws Exception {
   Box box= getProd(barcode);
   if (box== null) {
      showMsg("Коробки нет на складе");
      return;
   }
   if (box.ready) {
      showMsg("Коробка уже отсканирована");
      return;
   }
   ...   
}

To be honest, I like the first approach. The code is more concise. I know it's bad to put logic in the catch {} block, but it doesn't seem to be here. Based on other reviews, the try {} block has no performance impact as long as no exceptions are thrown.
Your opinion?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
A
aol-nnov, 2016-03-16
@aol-nnov

иди дальше!
throw new BoxNotFoundException
throw BoxAlreadyScannedException
:)

M
mitekgrishkin, 2016-03-16
@mitekgrishkin

Как вам самому удобно. Единственное - просто кидать Exception - это издевательство над тем, кто будет это дело сопровождать. В вашем случае можно создать что-то типа UserException - это позволит отличать ваши исключения от общих остальных. Заодно подключите вывод сообщения.

S
sirs, 2016-03-16
@sirs


if (box== null) throw new Exception("Box out of stock");
if (box.ready) throw new Exception("The box has already been scanned");
A bunch of ifs is not good. Why don't you just introduce the concept of State, create an Enum for it with all possible states, and apply a template like Strategy . For each specific state of the object, you will need to write a separate handler and not throw an Exception from the method, but simply transfer control to the desired handler.
As an alternative, look at the frameworks that allow you to organize the so-called. Route , you might like this implementation. If the box is in the warehouse - go along path 1, if the box is not in stock - go along path 2, if the code has already been read from the box - go along route 3, etc. Such an implementation, for example, will help to establish transactionality out of the box.

Денис Загаевский, 2016-03-16
@zagayevskiy Куратор тега Java

Нет, кидать исключения - однозначно плохой вариант. Само слово "исключение" говорит об этом - ситуации в приложении должны быть не нормой, а исключением для броска исключения. Исходите из этого постулата.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question