Anant Agarwal
Anant Agarwal

Reputation: 63

Does JVM throw exception to OS

I was asked this question that does JVM throw Exception to OS if main throws? JVM stops application execution but where this exception will be handled?

public static void main(String[] args) throws Exception {
    display();
}

public static void display() throws Exception {
    throw new RuntimeException();
}

If this can occur with any exception, please specify.

Upvotes: 3

Views: 550

Answers (2)

BurnetZhong
BurnetZhong

Reputation: 448

Java runs in JVM, so all exceptions will be handled in JVM. Simply for your answer, Java exceptions will not throw to OS level. In the other words, you cannot catch JAVA exceptions in OS level.

Hope this answers your question.

Upvotes: 0

Chris Hayes
Chris Hayes

Reputation: 12020

It is not handled by the OS, but by the JVM itself. From the Java language specification §11.3:

If no catch clause that can handle an exception can be found, then the current thread (the thread that encountered the exception) is terminated

Your JVM will be running with a single thread, which will be terminated. The JVM will then shut itself down, according to JLS §12.8 (emphasis added):

A program terminates all its activity and exits when one of two things happens:

  • All the threads that are not daemon threads terminate.
  • Some thread invokes the exit method of class Runtime or class System, and the exit operation is not forbidden by the security manager.

This can occur with any type of exception at all. Note that in terms of the language specification, an "exception" is actually a java.lang.Throwable and any of its subclasses. This means that Errors also terminate threads/JVMs, and anything else inheriting from Throwable, rather than just objects extending Exception.

Upvotes: 6

Related Questions