-1

I have a class FileLock, which checks and validates a file, and a method Validate

public class FileLock {
    public static void Validate(String conf_file) throws IOException{

My intention is whenever an IOException is encountered, it should terminate.

Now I have the test class to test this.

public class Test{
    public static void main(String[] args){
    String conf_file = args[0];
    FileLock.Validate(conf_file);

Now, this gives a compile time error saying Unhandled exception type IOException at the line FileLock.Validate(conf_file); If I add throws IOException along with main() as well, this error disappears. Why is that? What is the best way to do this?

scott
  • 1,557
  • 3
  • 15
  • 31
  • 5
    Read https://docs.oracle.com/javase/tutorial/essential/exceptions/catchOrDeclare.html – Jon Skeet Nov 19 '15 at 15:11
  • Thank you @JonSkeet, so I am supposed to use try catch block here. However, would you be kind enough to explain why I couldn't throw exception in the static method? – scott Nov 19 '15 at 15:18
  • You could catch the exception - or declare that `main` might throw the same exception. Those are the rules. If you didn't get that much from the page I linked to, I suggest you reread it again (and look for "checked exceptions" in whatever book you're learning Java from). – Jon Skeet Nov 19 '15 at 15:26

1 Answers1

2

When a method throws an exception, it expects the exception to be handled if it is thrown. You can handle exceptions with a try-catch block. In your case, this would look like:

try {
    FileLock.validate(conf_file);
} catch(IOException e) {
    //handle exception; e.printStackTrace() will print out error stack trace
}
Lucas Baizer
  • 305
  • 2
  • 5
  • 13
  • Why couldn't I throw the error in the static method? What is the logical error I did? – scott Nov 19 '15 at 15:20
  • You can throw the error in the static method. The error is when you call the method; if the exception is not caught and handled, then there is a compiler error. – Lucas Baizer Nov 20 '15 at 17:50