Generally we use "new" keyword for creating the object and I am aware that (String s = "Hello") will also create an object but in the catch block its just mentioned that catch(ArithmeticException e)
. How 'e' is an object here?
public static void main(String[] args) {
try {
int data=50/0; //may throw exception
}
//handling the exception
catch(ArithmeticException e) {
System.out.println(e);
}
System.out.println("rest of the code");
}
}
CodePudding user response:
The code here in the try block when throws an exception of type ArithmeticException, the object is what is created in the runtime. Hence, in the catch block, variable e becomes an object at runtime.
CodePudding user response:
I believe that you are asking how the ArithmeticException
is created in your example. (You are clearly not explicitly using new
to create it in this case.)
The answer is that the JVM creates it. When the JVM detects that an integer divide by zero occurs, it creates an instance of ArithmeticException
with the message string "divide by zero" (or some such) and then it throws it.
Q: How does it detect the divide by zero and how does it create and throw the exception?
A: All of those things are implementation specific1. But you won't see any specific bytecode instructions to do this if you disassemble the bytecodes. It is happening at a lower level. Conceptually, it happens inside the division instruction.
At any rate, the ArithmeticException
object does get created, and then the exception handler binds it (assigns it) to the e
variable.
1 - For example, on some hardware an integer divide by zero triggers an interrupt. This will be caught by the OS exception handlers which signals the JVM. Eventually, the signal handler (deep in the JVM) figures out which thread did it, creates the exception object and "throws" it. It is messy complicated low-level stuff ... that you don't need to know about when writing Java programs.