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


What will be the output when you compile and execute the


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

What will be the output when you compile and execute the
following code?
class Test {
try {
System.out.println(“This is try block”);
}
System.out.println(“Try block is executed”); //Line
1
catch(Exception exp) {
System.out.println(“This is catch block”);


123.
}
}
Answer:
The above code will not compile and will throw a compilation
error. This is because the code at Line 1 is written after the end of
try block but before the catch block. All the code needs to be
written either inside the try block or the catch block. Java does
not allow code in between the try and catch blocks.
Write a code sample that demonstrates the
try/catch/finally block.
Answer:
Following is a code sample that demonstrates the try/catch/finally
block:
try {
System.out.println(“This is try block”);
} catch {
System.out.println(“This is catch block”);
}
finally {
System.out.println(“This is finally block”);
}
All the code that needs to be monitored for exceptions should be
placed within the try block. Immediately following the try block,
you need to specify a catch clause. In the catch block, you need
to specify the exception type that you wish to catch and the code
that you want to be executed when that exception occurs. The
finally clause is optional and it needs to be placed either after the
try or catch block. Any code that needs to be executed always


124.
125.
irrespective of whether an exception occurs or not should be
placed in the finally clause.
What will be the output on executing the code below?
class ExceptionTest {
public static void main(String argument[]) {
callMethod();
}
static void callMethod() {
int intValue = 100 / 0;
System.out.println(“intValue is: ”+intValue);
}
}
Answer:
The above code gets compiled without any errors. However, on
executing it throws an ArithmeticException with a stack
trace (Error information or report) as shown below:
Exception in thread “main” java.lang.Arithmetic
Exception– / by zero
at ExceptionTest.callMethod(ExceptionTest.java:12)
at ExceptionTest.main(ExceptionTest.java–9)
This is because dividing a number by 0 is not allowed.

Download 1.52 Mb.

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




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