Помогите оптимизировать метод обработки exeption в Java
Помогите оптимизировать метод обработки исключений:
public void myException() throws IllegalStateException, Exception, RuntimeException
{
System.out.println("Start");
try
{
System.out.println("Step 1");
throw new IllegalArgumentException();
}
catch (IllegalArgumentException e)
{
System.out.println("Catch IllegalArgumentException");
throw new RuntimeException("Step 2");
}
catch (RuntimeException e)
{
System.out.println("Catch RuntimeException");
throw new RuntimeException("Step 3");
}
finally
{
System.out.println("Step finally");
throw new RuntimeException("From finally");
}
}
Насколько я понимаю
- Два раза бросаем RuntimeExeption, в последнем блоке catch и в finaly.
- Избыточная конструкция try, catch с trow new и trows в сигнатуре метода.
- ..
Ответы (2 шт):
Автор решения: Nordfox
→ Ссылка
вот так?
import java.io.IOException;
//...
public void myException() throws IllegalStateException, IOException, RuntimeException
{
System.out.println("Start");
try
{
System.out.println("Step 1");
}
catch (IllegalArgumentException e)
{
System.out.println("Catch IllegalArgumentException");
throw new RuntimeException("Step 2");
}
catch (RuntimeException e)
{
System.out.println("Catch RuntimeException");
throw new RuntimeException("Step 3");
}
finally
{
System.out.println("Step finally");
}
}
Автор решения: Roman Konoval
→ Ссылка
Если выбросить все что не влияет никак на видимый конечный результат, то получим:
public void myException() throws IllegalStateException, Exception, RuntimeException
{
System.out.println("Start");
System.out.println("Step 1");
System.out.println("Catch IllegalArgumentException");
System.out.println("Step finally");
throw new RuntimeException("From finally");
}