Java Thread Interview Questions and Answers

    6 Votes

28) Can you explain about Exception handler in Java ?

Java have powerful Exception handling. The try-catch-finally block is used to handle the exception.

try // The code in which the exception may occur is enclosed in a try block
catch(Exception e) // The catch clause matches a specific exception to a block of code which handles that exception.
finally // Clean up code which needs to be executed no matter the exception occurs or not is put inside the finally block

Throw : Used to declare an exception.

throw new Exception("Something went wrong!");

Throws : Used to throw an exception explicitly.

public void mathFunction() throws IOException,ArithmeticException

29) Can you explain about java.lang.RuntimeException class ?

Exceptions that happen at runtime due to programming errors is called RuntimeException. It will be good, if the programmer checks for this exception during code review. If we want to handle run time exception in each and every code block, clarity of program will be reduced drastically. Ex: Arithmetic exceptions, such as dividing by zero

30) Can you explain about java.lang.throwable class ?

All the errors and exception handling classes in Java are derived from super class "java.lang.Throwable". JVM throws exception created by Throwable class objects or it's subclass objects.

31) Can you explain the exception class hierarchy ?

Main exception class is Throwable. Other classes that inherit Throwable class are Checked exceptions and Unchecked Exceptions.

32) Can you explain about IndexOutOfBoundExecption classes and it sub classes ?

It's under RuntimeException. Two classes that inherit IndexoutOfBoundException are "StringIndexOutOfBoundsException" and "ArrayIndexOutOfBoundsException".

33) Can you explain about OutOfMemoryError ?

OutOfMemoryError is a serious problem created by the memory limitation of the machine. In some cases, programming errors cause memory leak and in turn creates "OutOfMemoryError". Whatever be the reason for memory shortage, when the JVM is not able to create and object or garbage collector is not in a position to release memory, out of memory error is thrown.

34) Can write a program to create manual exception class ?

To create you own exception extend the Exception class or any of its subclasses.

class FirstException extends Exception { }

35) How to avoid NullPointerException in java ?

NullPointerException is an unchecked exception. Code to handle exception is as shown below

Object mayBeNullObj = getTheObjectItMayReturnNull();

if (mayBeNullObj != null) { // to avoid NullPointerException
Page 4 of 4

Popular Videos


How to improve your Interview, Salary Negotiation, Communication & Presentation Skills.

Got a tip or Question?
Let us know

Related Articles

Java OOPS Interview Questions and Answers
Java Interview Questions
Top Advanced Java Interview Questions and Answers
Java Collections Interview Questions and Answers