0

A few days back we had a lecture on try catch and finally blocks , I'm however wondering how does JVM process the Try catch and finally codes. Cause if there is a exception being generated , then how does catch resolve it. And what happens inside each block during exception handling and exception generation. How does the system know that the result obtained is an exception and not a legit output .What exactly is happening inside the pc when a try catch block is being executed.

would be a great help if someone could tell me these concepts .

kushal
  • 301
  • 1
  • 7
  • 18

2 Answers2

1

The catch doesn't necessarily "resolve it". The catch is used to process code when the exception occurs. You could put whatever valid code you want in the catch block.

In a try block the code is executed line by line if an exception occurs in the line an exception will be thrown. The catch block is then used to catch the exception and handle it. If the exception is not caught then it will cause a runtime error. The execution in the try block will stop at whatever point the exception occurs in the try block an will not finish processing the rest of the try block. It will jump straight to the catch block to process the code for that particular exception.

A finally block is used to execute a block of code regardless of whether an exception has occurred or not. The finally block will always be executed whether or not an exception occurs as long as the exception is caught.

brso05
  • 13,142
  • 2
  • 21
  • 40
  • but how does the JVM come to know about an exception..?? There has to be some way of it knowing right..? ( at more of a lower level) – kushal Dec 17 '14 at 16:52
  • An exception is **thrown** you can even try in your code `throw new Exception();` this will manually throw an exception at that line. – brso05 Dec 17 '14 at 16:56
  • Whatever line of code your executing would throw an exception and it would move up the stack if not handled until it reaches the top and causes a runtime error. – brso05 Dec 17 '14 at 16:56
0

Generally when any problem or error occurs in the statement which are in try block it is directly redirected to catch block for getting which type of exception is there. If the exception has got it's handler than it handles it otherwise error.