Core java interview Questions You'll Most Likely Be Asked (Second Edition)


Explain the try–catch–finally statement in Java


Download 1.52 Mb.
Pdf ko'rish
bet49/171
Sana07.01.2023
Hajmi1.52 Mb.
#1081886
1   ...   45   46   47   48   49   50   51   52   ...   171
Bog'liq
Core JAVA Interview Questions Youll M...

Explain the try–catch–finally statement in Java.
Answer:
The Try–Catch–Finally statement allows exception handling in
Java. You can put the statements that that you would like to
monitor for errors within the try block. The code that needs to be


126.
executed in case an exception occurs should be placed within the
catch block. You also need to specify the type of exception that
you wish to catch. You can specify multiple catch blocks for
different types of exceptions. Following the catch block, you can
specify the finally block. Here, you need to put in code that you
need to be executed irrespective of whether an exception is
thrown or not. The catch and finally blocks are optional, but you
need to have either one of them.
The following code demonstrates the try–catch–finally statement:
try {
// Code to be monitored for exceptions
}
catch (ExceptionType 1) {
// Instructions to follow if an exception occurs
}
catch (ExceptionType 2) {
// Instructions to follow if an exception occurs
}
catch (ExceptionType n) {
// Instructions to follow if an exception occurs
}
finally {
// this block is definitely executed even if an
exception is thrown or not
}
What will be the output of the following code snippet?
public class MyClass1 {
public static void main(String abc[]) {


try {
int no;
no = 52 / 0; //Line 1
} catch (ArithmeticException e) { //Line 2
System.out.println(“ArithmeticException”);
} catch (ArrayIndexOutOfBoundsException e) { //Line 3
System.out.println(“Array Out Of Bound”);
} catch (Exception e) { // any other exception //Lin2
4
System.out.println(“Sorry Unhandled Exception”);
} finally { // this will be executed //Line 5
System.out.println(“I am done!”);
}
System.out.println(“Thank You!!”); //Line 6
}
}
}
Answer:
This code prints the following output:
ArithmeticException
I am done!
Thank You!!
Line 1 causes an ArithmeticException. This is caught by the
ArithmeticException catch block at Line 2 which prints the
text ArithmeticException. Since finally block is always
executed, irrespective of whether an error occurs or not, the
control then transfers to the finally block at Line 5 and prints I am



Download 1.52 Mb.

Do'stlaringiz bilan baham:
1   ...   45   46   47   48   49   50   51   52   ...   171




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling