Learnitweb

What happens when exception is thrown by main method?

When program starts, the JVM sets a default uncaught exception handler that prints the exception to standard console and terminates. So when exception is thrown by main method then JVM prints the exception to standard console and terminates.

  • It is valid to add throws with main method.
  • The rules for exception for main method is same as it is for other methods.
  • When throws is added to method declaration then it is the responsibility of the calling method to handle exception. Here JVM calls the main method, so thrown exception is handled by JVM.

import java.io.FileNotFoundException;

public class ExceptionInMainExample {

	public static void main(String[] args) throws FileNotFoundException {
		throw new FileNotFoundException();
	}
}

Output

Exception in thread "main" java.io.FileNotFoundException
	at IteratorRemoveExample.main(IteratorRemoveExample.java:6)