Thursday, June 17, 2010

Java Interview Question 3

<< Previous                                                                                    Next  >>

Java Interview Question 8:
How does Java handle exceptions using try –catch block?

When an exceptional event occurs in Java, an exception is said to be "thrown." The code that's responsible for doing something about the exception is called an "exception handler," and it "catches" the thrown exception. Exception handling works by transferring the execution of a program to an appropriate exception handler when an exception occurs. We need a way to tell the JVM what code to execute when a certain exception happens. To do this, we use the try and catch keywords. The try is used to define a block of code in which exceptions may occur. This block of code is called a guarded region (which really means "risky code goes here"). If an exception occurs within the try block, that exception is handled by an exception handler associated with it. To associate an exception handler with a try block, we must put a catch block after it. The catch block contains the code that is executed in exceptional circumstances. We can associate exception handlers with a try block by providing one or more catch blocks directly after the try block. No code can be between the end of the try block and the beginning of the first catch block.


Java Interview Question 9:
What is the use of the finally block?


Finally is the block of code that needs to be executed under any circumstance. The code in finally block will execute even if an exception is occurred. When an exception is thrown, the statements in the try block written after the statement in which the exception occurred are ignored. The finally block is used to process certain statements, no matter whether an exception is thrown or not. "Finally" creates a block of code that will be executed after try/catch block has completed and before the code following the try/catch block. If there is a catch block associated with the try block, the finally clause is executed after the catch block. If an exception is thrown, finally block will execute even if no catch statements matches the exception. Finally is guaranteed to execute, even if no exceptions are thrown. Finally block is an ideal position for closing the resources such as file handle or a database connection etc.
Java Interview Question 10:
What are transient variables in java?

Transient variables are variable that cannot be serialized.

<< Previous                                                                             Next  >>

No comments: