Java Interview Questions and Answers for 3 Years Experience - 1

Question: 1

Explain the user defined exceptions?

User defined exceptions are custom exception classes defined by the user for specific purpose.

A user defined exception can be created by simply sub classes an exception class or a sub class of an exception class.

This allows custom exceptions to be generated (using throw clause) and caught in the same way as normal exception.


class customexception extends exception



Question: 2

What are the different ways to handle exceptions?

There are two ways to handle exceptions,

By wrapping the desired code in a try block followed by a catch block to catch the exceptions. and

List the desired exceptions in the throws clause of the method and let the caller of the method handle those exceptions.

Question: 3

What are important methods of Java Exception Class?

Exception and all of its subclasses doesn’t provide any specific methods and all of the methods are defined in the base class Throwable.

Strings getMessage() – This method returns the message String of Throwable and the message can be provided while creating the exception through it’s constructor.

Strings getLocalizedMessage() – This method is provided so that subclasses can override it to provide locale specific message to the calling program. Throwable class implementation of this method simply use getMessage() method to return the exception message.

Synchronized Throwable getCause() – This method returns the cause of the exception or null id the cause is unknown.

String toString() – This method returns the information about Throwable in String format, the returned String contains the name of Throwable class and localized  message.

Void printStackTrace() – This method prints the stack trace information to the standard error stream, this method is overloaded and we can pass PrintStream or PrintWriter as argument to write the stack trace information to the file or stream.

Question: 4

What is exception in java?

Exception is an error event that can happen during the execution of a program and disrupts its normal flow.

Exception can arise from different kind of situations such as wrong data entered by user, hardware failure, network connection failure etc.

Whenever any error occurs while executing a java statement an exception object is created and then JRE tries to find exception object is passed to the handler code to process the exception, known as catching the exception.

If no handler is found then application throws the exception to runtime environment and JRE terminates the program.

Java Exception handling framework is used to handle runtime errors only, compile time errors are not handled by exception handling framework.

Question: 5

What is the purpose of the finally of a try catch finally statements?

The finally clause is used to provide the capability to execute code no matter whether or not an exception is thrown or caught.

Related Questions