0
try 
{
}
catch(ExceptionType name)
{
}

One thing that I'm particularly unable to understand is the argument of Catch Block. We write "catch(ExceptionType name)" What exactly is "name" though? If "ExceptionType" is class, shouldn't "name" be reference to an object? Even if it is a reference, since we haven't created any object, what exactly does it contain?

Now I have come up with this theory regarding Exception Handling - please correct me I'm getting it wrong.

CASE 1 - SUPPOSING NO TRY, CATCH BLOCK EXISTS - If an error occurs, the exception handler automatically generates an exception object[based on exception's class] and hands it over to the JVM and then JVM then returns the function or crashing error to be displayed at the run-time

CASE 2 - IF PROGRAMMER HAS WRITTEN A TRY CATCH BLOCK - If an error occurs, the exception handler generates an exception object[based on exception's class] and then instead of going to the JVM, it will first look into the catch block and try to match the reference variable to the exception object. If the match happens, exception handler hands that object to the catch block reference and then programmer can return the function of his or her choice. However, if the match does not happen, exception handler will hand that exception object back to the JVM.

Is this how Exception Handling work?

nSack
  • 65
  • 7
  • Neither: The exception object is generated with `new SomeException()`, and the exception handler _catches the existing exception object_. – chrylis -cautiouslyoptimistic- Jul 11 '21 at 04:56
  • 3
    *"What exactly is "name" though?"* `name` is like a **local variable**, that is assigned the exception that was thrown. Or you can think of it as a method parameter. --- *"shouldn't "name" be reference to an object?"* It is. --- *"we haven't created any object"* Correct, the JVM did. – Andreas Jul 11 '21 at 04:56
  • What about the 2 cases that I thought of Andreas? – nSack Jul 11 '21 at 05:02
  • Case 1 above I'm pretty sure is just a syntax error. You can't have a `catch` without a `try`. Case 2 is pretty close, but if the exception is checked then you have to declare it in your method if you don't catch it. *"Hands it to the JVM"* is kind of weird in my opinion. What the JVM does is unwind the call stack one method at a time, checking each method for a `catch`. So you should think of each method having a chance to handle the exception. – markspace Jul 11 '21 at 05:32
  • Hey mark, I think I understood the case 2 well. But in the case 1, I meant no try and no catch - NO EXCEPTION HANDLING WHATSOEVER. What I wanted to know in case 1 is that - when the user has not defined any exception handling, what does JVM do then? How similar and how different is it from case 2. – nSack Jul 11 '21 at 05:41

4 Answers4

3

What exactly is "name" though?

name is like a local variable, that is assigned the exception that was thrown. Or you can think of it as a method parameter.

If "ExceptionType" is class, shouldn't "name" be reference to an object?

Both are: ExceptionType is a class, and name is an object reference.

we haven't created any object, what exactly does it contain?

Whatever logic that threw the exception, created it using the new operator, which is why the throw statement is almost always immediately followed by the new operator, e.g. throw new IllegalArgumentException().

If it's a built-in exception (like NullPointerException, StackOverflowError, ArrayIndexOutOfBoundsException, etc.), the the JVM runtime created the exception.

CASE 1 - SUPPOSING NO TRY, CATCH BLOCK EXISTS
CASE 2 - IF PROGRAMMER HAS WRITTEN A TRY CATCH BLOCK
If an error occurs, the exception handler automatically generates an exception object ...

Your terminology is off: An "exception handler" is code that handles a thrown exception. See e.g. UncaughtExceptionHandler.

If an error occurs, an exception is created and thrown by the JVM runtime, regardless of whether or not there is a try-catch statement.

From there on, the handling of the exception is the same, regardless of whether the exception was thrown by the system, or us a user-defined exception thrown by the throw statement.

Andreas
  • 154,647
  • 11
  • 152
  • 247
  • "If an error occurs, an exception is created and thrown by the JVM runtime" But to where? If the catch block doesn't exist - like I said in case 1 - then how is the exception handled? – nSack Jul 11 '21 at 05:48
  • @nSack Exceptions aren't thrown *to* anywhere, they are thrown *from* the place where they occur. From there, the JVM will start unwinding the call stack, checking if any `catch` clauses can handle the exception. If no `catch` clause is found, the exception will be handled by the *Uncaught Exception Handler*. – Andreas Jul 11 '21 at 17:00
3

Let me explain How JVM handles an Exception? Whenever inside a method, if an exception has occurred, the method creates an Object known as Exception Object and hands it off to the run-time system(JVM). This exception object contains the details of that particular exception and the current state of the program where an exception has occurred. Creating the Exception Object and handling it to the run-time system is called throwing an Exception. There might be a list of the methods that had been called to get to the method where an exception has occurred. This ordered list of the methods is called Call Stack. Now the following procedure will happen.

  • The run-time system searches the call stack to find the method that contains a block of code that can handle the occurred exception. The block of the code is called an Exception handler.
  • The run-time system starts searching from the method in which exception occurred, proceeds through call stack in the reverse order in which methods were called.
  • If it finds an appropriate handler then it passes the occurred exception to it. Appropriate handler means the type of the exception object thrown matches the type of the exception object it can handle.
  • If the run-time system searches all the methods on the call stack and couldn’t have found the appropriate handler then the run-time system handover the Exception Object to the default exception handler, which is part of the run-time system. This handler prints the exception information in the following format and terminates the program abnormally.

Now how flow control work in try catch finally block in java

  1. Control flow in try-catch clause OR try-catch-finally clause: a. Case 1: Exception occurs in a try block and is handled in the catch block. b. Case 2: Exception that occurs in try-block is not handled in the catch block. c. Case 3: Exception doesn’t occur in try-block

  2. try-finally clause a. Case 1: Exception occurs in the try block. b. Case 2: Exception doesn’t occur in try-block.

For more information regarding the flow control work in the try-catch-finally block you can refer to this link

  • "Appropriate handler means the type of the exception object thrown matches the type of the exception object it can handle." But we never create any object, do we? All we write in catch block is an exception name[class name] and a reference variable. So what is exactly is JVM trying to match the exception object with? It's required class's reference variable? – nSack Jul 11 '21 at 05:51
  • Each catch block is an exception handler that handles the type of exception indicated by its argument. The argument type, ExceptionType, declares the type of exception that the handler can handle and must be the name of a class that inherits from the Throwable class. The handler can refer to the exception with name. – Harshil Kansagara Jul 11 '21 at 16:41
  • "This handler prints the exception information in the following format and terminates the program abnormally." Could you explain that format? You seem to have missed that part while explaining. – nSack Jul 12 '21 at 03:21
1

If ExceptionType is class, shouldn't name be reference to an object? Even if it is a reference, since we haven't created any object, what exactly does it contain?

The simple answer to your question / misunderstanding is that catching an exception does NOT create an exception object. Rather, the exception object was created earlier.

When you do this:

 throw new SomeException("message");

the new is explicitly creating an exception object.

When you do this:

SomeClass foo = null;
foo.someMethod();

the JVM will create a NullPointerException object.

In either case, it will be those objects that are assigned to the variable in the catch clause; name in your example.


This also indirectly explains something else. When you call printStackTrace() on an exception object, it will (apparently) print the stack trace for the point at which the exception was thrown.

How does it manage this?

Well actually, what I said above was slightly incorrect. What it is actually printing is the stacktrace for the point at which the exception object was created! (The two points are usually the same, but not always.)

What actually happens is that when the exception object is created (by new, by the JVM, or by native code) the constructor for Throwable (the ancestor class of all exception classes) calls a method called fillInStackTrace(). This in turn calls an internal method that populates an array with the stack frame information for the current call context.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
0

If I fully understood your question, this may be what you're looking for. Since Java is an interpreted language, when the JVM finds the correct error while executing the bytecode, it will jump to the bytecode for the block that you wrote in the except block, making a new SomeException(), which is basically an object of information about the error, and passes it as that local variable parameter, in your code ExceptionType name.

Referencing your example of no try / catch, it would have to just throw an error, print stack trace, and exit with an error, and no SomeException object is instantiated. Hope I can help. Some links that may be of interest are here, here, and maybe here (similar question).

Juicestus
  • 442
  • 1
  • 7
  • 14
  • But to print stack trace or any message, JVM will have to call the printStackTrace function and for that, it requires an object of that exception class? So I'm assuming new SomeException() is called in both the cases? Only that in the first case, printStackTrace function gets automatically called while in second, the object gets transferred to our reference variable and we decide what we wish to call? – nSack Jul 11 '21 at 05:15