0% found this document useful (0 votes)
1 views

Exception Handling

The document provides a comprehensive overview of exception handling in Java, detailing the definitions, mechanisms, and differences between errors and exceptions. It explains the structure of try, catch, and finally blocks, along with various types of exceptions such as checked and unchecked exceptions. Additionally, it covers advanced topics like re-throwing exceptions, the use of the throws keyword, and the introduction of try-with-resources in Java 7.

Uploaded by

dhaneshsudha996
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

Exception Handling

The document provides a comprehensive overview of exception handling in Java, detailing the definitions, mechanisms, and differences between errors and exceptions. It explains the structure of try, catch, and finally blocks, along with various types of exceptions such as checked and unchecked exceptions. Additionally, it covers advanced topics like re-throwing exceptions, the use of the throws keyword, and the introduction of try-with-resources in Java 7.

Uploaded by

dhaneshsudha996
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Excep on Handling

1) What is an exception?

Exception is an abnormal condition which occurs during the execution of a program and disrupts
normal flow of a program. This exception must be handled properly. If it is not handled, program
will be terminated abruptly.

2) How the exceptions are handled in Java? OR Explain exception handling mechanism in
Java?

Exceptions in Java are handled using try, catch and finally blocks.

try block : The code or set of statements which are to be monitored for exception are kept in this
block.

catch block : This block catches the exceptions occurred in the try block.

finally block : This block is always executed whether exception is occurred in the try block or not
and occurred exception is caught in the catch block or not.

3) What is the difference between error and exception in Java?

Errors are mainly caused by the environment in which an application is running. For
example, OutOfMemoryError happens when JVM runs out of memory. Where as exceptions are
mainly caused by the application itself. For example, NullPointerException occurs when an
application tries to access null object.

4) Can we keep other statements in between try, catch and finally blocks?

No. We shouldn’t write any other statements in between try, catch and finally blocks.

1
2try
3{
4 // Statements to be monitored for exceptions
}
5
6
7//You can't keep statements here
8
catch(Exception ex)
9
{
10 //Catching the exceptions here
11}
12
13//You can't keep statements here
14
15finally
16{
17 // This block is always executed
18}
5) Can we write only try block without catch and finally blocks?

No, it shows compilation error. The try block must be followed by either catch block or finally
block.

Note : From Java 7, with the introduction of try-with resources blocks, we can write only try block
without catch and finally blocks provided resources must be Auto Closeable.

6) There are three statements in a try block – statement1, statement2 and statement3.
After that there is a catch block to catch the exceptions occurred in the try block. Assume
that exception has occurred in statement2. Does statement3 get executed or not?

No, statement3 is not executed. Once a try block throws an exception, remaining statements will
not be executed. Control comes directly to catch block.

7) What is unreachable catch block error?

When you are keeping multiple catch blocks, the order of catch blocks must be from most
specific to general ones. i.e sub classes of Exception must come first and super classes later. If
you keep super classes first and sub classes later, compiler will show unreachable catch block
error.

1
2public class ExceptionHandling
3{
4 public static void main(String[] args)
5 {
6 try
7 {
8 int i = Integer.parseInt("abc"); //This statement throws NumberFormatException
9 }
10
11 catch(Exception ex)
{
12
System.out.println("This block handles all exception types");
13
}
14
15
catch(NumberFormatException ex)
16 {
17 //Compile time error
18 //This block becomes unreachable as
19 //exception is already caught by above catch block
20 }
21 }
22}
8) Explain the hierarchy of exceptions in Java?

9) What are run time exceptions in Java. Give example?

The exceptions which occur at run time are called as run time exceptions. These exceptions are
unknown to compiler. All sub classes of java.lang.RunTimeException and java.lang.Error are
run time exceptions. These exceptions are unchecked type of exceptions. For
example, NumberFormatException, NullPointerException, ClassCastException, ArrayIndexOutOf
BoundException, StackOverflowError etc.

10) What is OutOfMemoryError in Java?

OutOfMemoryError is the sub class of java.lang.Error which occurs when JVM runs out of
memory.
11) what are checked and unchecked exceptions in java?

Checked exceptions are the exceptions which are known to compiler. These exceptions are
checked at compile time only. Hence the name checked exceptions. These exceptions are also
called compile time exceptions. Because, these exceptions will be known during compile time
itself.

Unchecked exceptions are those exceptions which are not at all known to compiler. These
exceptions occur only at run time. These exceptions are also called as run time exceptions. All
sub classes of java.lang.RunTimeException and java.lang.Error are unchecked exceptions.

12) What is the difference between ClassNotFoundException and NoClassDefFoundError


in Java?
ClassNotFoundException NoClassDefFoundError

It is an exception. It is of type
It is an error. It is of type java.lang.Error.
java.lang.Exception.

It occurs when Java runtime system


It occurs when an application tries to load
doesn’t find a class definition, which is
a class at run time which is not updated in
present at compile time, but missing at
the classpath.
run time.

It is thrown by the application itself. It is


thrown by the methods like
It is thrown by the Java Runtime System.
Class.forName(), loadClass() and
findSystemClass().

It occurs when classpath is not updated It occurs when required class definition is
with required JAR files. missing at run time.

13) Can we keep the statements after finally block If the finally block is returning the
control?

No, it gives unreachable code error. Because, control is returning from the finally block itself.
Compiler will not see the statements after it. That’s why it shows unreachable code error.

14) Does finally block get executed If either try or catch blocks are returning the control?

Yes, finally block will be always executed no matter whether try or catch blocks are returning the
control or not.

15) Can we throw an exception manually? If yes, how?

Yes, we can throw an exception manually using throw keyword. Syntax for throwing an exception
manually is

throw InstanceOfThrowableType;

Below example shows how to use throw keyword to throw an exception manually.

1
try
2
{
3 NumberFormatException ex = new NumberFormatException(); //Creating an object to Number
4
5 throw ex; //throwing NumberFormatException object explicitly using throw keyword
6}
7catch(NumberFormatException ex)
8{
9 System.out.println("explicitly thrown NumberFormatException object will be caught here");
10}
16) What is Re-throwing an exception in Java?

Exceptions raised in the try block are handled in the catch block. If it is unable to handle that
exception, it can re-throw that exception using throw keyword. It is called re-throwing an
exception.

1
2try
{
3
String s = null;
4 System.out.println(s.length()); //This statement throws NullPointerException
5}
6catch(NullPointerException ex)
7{
8 System.out.println("NullPointerException is caught here");
9
10 throw ex; //Re-throwing NullPointerException
11}

17) What is the use of throws keyword in Java?

throws keyword is used to specify the exceptions that a particular method can throw. The syntax
for using throws keyword is,

1return_type method_name(parameter_list) throws exception_list


2{
3 //some statements
4}

18) Why it is always recommended that clean up operations like closing the DB resources
to keep inside a finally block?

Because finally block is always executed whether exceptions are raised in the try block or not
and raised exceptions are caught in the catch block or not. By keeping the clean up operations in
finally block, you will ensure that those operations will be always executed irrespective of
whether exception is occurred or not.

19) What is the difference between final, finally and finalize in Java?

final finally finalize()

finally is a block in
final is a keyword in finalize() method is a protected
Java which is used
Java which is used to method of java.lang.Object class
for exception
make a variable or a which is used to perform some clean
handling along with
method or a class as up operations on an object before it
try and catch
unchangeable. is removed from the memory.
blocks.
finally block is
always executed
The value of a variable
whether an This method is called by garbage
which is declared as
exception is collector thread before an object is
final can’t be changed
occurred or not and removed from the memory.
once it is initialized.
occurred exception
is handled or not.

Most of time, this


A method declared as
block is used to
final can’t be
close the resources
overridden or modified This method is inherited to every
like database
in the sub class and a class you create in Java.
connection, I/O
class declared as final
resources etc soon
can’t be extended.
after their use.

20) What is the difference between throw, throws and throwable in Java?

throw throws Throwable

throws is also a
keyword in java
Throwable is a super
which is used in
class for all types of
the method
throw is a keyword in Java which is errors and exceptions in
signature to
used to throw an exception manually. Java. This class is a
indicate that this
member
method may
of java.lang package.
throw mentioned
exceptions.

The caller to
such methods
Using throw keyword, you can throw Only instances of this
must handle the
an exception from any method or class or it’s sub classes
mentioned
block. But, that exception must be of are thrown by the java
exceptions either
type java.lang.Throwable class or virtual machine or by the
using try-catch
it’s sub classes. throw statement.
blocks or using
throws keyword.

21) What is StackOverflowError in Java?

StackOverflowError is an error which is thrown by the JVM when stack overflows.

22) Can we override a super class method which is throwing an unchecked exception with
checked exception in the sub class?
No. If a super class method is throwing an unchecked exception, then it can be overridden in the
sub class with same exception or with any other unchecked exceptions but can not be overridden
with checked exceptions.

23) Which class is the super class for all types of errors and exceptions in Java?

java.lang.Throwable is the super class for all types of errors and exceptions in Java.

24) What are the legal combinations of try, catch and finally blocks?

1)

1
try
2{
3 //try block
4}
5catch(Exception ex)
6{
7 //catch block
8}
2)

1
try
2{
3 //try block
4}
5finally
6{
7 //finally block
8}
3)

1
2try
3{
//try block
4
}
5
catch(Exception ex)
6{
7 //catch block
8}
9finally
10{
11 //finally block
12}

25) What is the use of printStackTrace() method?

printStackTrace() method is used to print the detailed information about the exception occurred.

26) Give some examples to checked exceptions?


ClassNotFoundException, SQLException, IOException

27) Give some examples to unchecked exceptions?

NullPointerException, ArrayIndexOutOfBoundsException, NumberFormatException

28) Do you know try-with-resources blocks? Why do we use them? When they are
introduced?

Try-with-resources blocks are introduced from Java 7 to auto-close the resources like File I/O
streams, Database connection, network connection etc… used in the try block. You need not to
close the resources explicitly in your code. Try-with-resources implicitly closes all the resources
used in the try block.

29) What are the benefits of try-with-resources?

The main benefit of try-with-resources is that it avoids resource leaks that could happen if we
don’t close the resources properly after they are used. Another benefit of try-with-resources is
that it removes redundant statements in the code and thus improves the readability of the code.

30) What are the changes made to exception handling from Java 7?

Multi-catch exceptions and try-with-resources are two major changes made to exception handling
from Java 7.

31) What are the differences between StackOverflowError and OutOfMemoryError In


Java?

StackOverflowError OutOfMemoryError

It is related to Stack memory. It is related to heap memory.

It occurs when Stack is full. It occurs when heap is full.

It is thrown when you create a new


It is thrown when you call a method and
object and there is no space left in the
there is no space left in the stack.
heap.

It occurs when you are calling a method


It occurs when you are creating lots of
recursively without proper terminating
objects in the heap memory.
condition.

How to avoid? How to avoid?


Make sure that methods are finishing their Try to remove references to objects
execution and leaving the stack memory. which you don’t need anymore.

You might also like