Good day. Solved the learning task

public class Solution { public static StatelessBean BEAN = new StatelessBean(); public static void main(String[] args) throws FileSystemException { try { processExceptions(); } catch (FileSystemException f) { BEAN.log(f); } } public static void processExceptions() throws FileSystemException { try { BEAN.methodThrowExceptions(); } catch (FileSystemException f) { BEAN.log(f); throw f; } catch (CharConversionException c) { BEAN.log(c); } catch (IOException i) { BEAN.log(i); } } public static class StatelessBean { public void log(Exception exception) { System.out.println(exception.getMessage() + ", " + exception.getClass().getSimpleName()); } public void methodThrowExceptions() throws CharConversionException, FileSystemException, IOException { int i = (int) (Math.random() * 3); if (i == 0) throw new CharConversionException(); if (i == 1) throw new FileSystemException(""); if (i == 2) throw new IOException(); } } } 

The task was not accepted due to the fact that the signature of the main() method does not need to specify the class of the throws FileSystemException thrown into it. Please explain why you can not do this.

  • one
    throws is used to indicate a possible exception. Moreover, if the exception is unchecked, then in fact you simply designate it for reading information about the method (ie, no one obliges you to do it, but this is sometimes accepted). If an exception of type is checked, then it remains for you to either process it inside the method, or “flip” it upward using throws to process the above. However, in this way, if all the time "throwing" the exception above you get to the main () method, which has nowhere to "throw" and the application will pause. In normal applications, this is unacceptable. - I. Perevoz
  • Thank you, you have explained a lot - Roman DriveMind
  • Specifically, in this case, throws FileSystemException from the main not necessary, because the method does not throw it. - zRrr

1 answer 1

Your code should never fall. He should issue a message that something went wrong, can close, but should not tell the system that he has broken. This is bad form. Imagine that you have created an application in which you can write the name of a person and his date of birth. When parsing the date, you found that the user entered a comma instead of a period, and instead of giving the user a warning / error message, you completely drop it. It turns out bad

  • if I understand you correctly, then: we indicate trows only if we are going to move it further? - Roman DriveMind
  • Yes. As I recall, this is an indication of what exceptions may return from this method. - Trymount