SlideShare a Scribd company logo
Java	
  Interview	
  Questions	
  –	
  www.JavaInterview.in	
   1	
  
	
  
Exception	
  Handling	
  
Explain	
  about	
  Exception	
  Handling	
  with	
  an	
  example.	
  
Exception Handling helps us to recover from an unexpected situations – File not found or network
connection is down. The important part in exception handling is the try – catch block. Look at the example
below.
	
  	
  	
  	
  public	
  static	
  void	
  main(String[]	
  args)	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  method1();	
  
	
  	
  	
  	
  	
  	
  	
  	
  System.out.println("Line	
  after	
  Exception	
  -­‐	
  Main");	
  
	
  	
  	
  	
  }	
  
	
  
	
  	
  	
  	
  private	
  static	
  void	
  method1()	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  method2();	
  
	
  	
  	
  	
  	
  	
  	
  	
  System.out.println("Line	
  after	
  Exception	
  -­‐	
  Method	
  1");	
  
	
  	
  	
  	
  }	
  
	
  
	
  	
  	
  	
  private	
  static	
  void	
  method2()	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  try	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  String	
  str	
  =	
  null;	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  str.toString();	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  System.out.println("Line	
  after	
  Exception	
  -­‐	
  Method	
  2");	
  
	
  	
  	
  	
  	
  	
  	
  	
  }	
  catch	
  (Exception	
  e)	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  //	
  NOT	
  PRINTING	
  EXCEPTION	
  TRACE-­‐	
  BAD	
  PRACTICE	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  System.out.println("Exception	
  Handled	
  -­‐	
  Method	
  2");	
  
	
  	
  	
  	
  	
  	
  	
  	
  }	
  
	
  	
  	
  	
  }	
  
Program	
  Output	
  
Exception Handled - Method 2
Line after Exception - Method 1
Line after Exception - Main
When exception is handled in a method, the calling methods will not need worry about that exception.
Since Exception Handling is added in the method method2, the exception did not propogate to method1
i.e. method1 does not know about the exception in method2.
Few important things to remember from this example.
• If exception is handled, it does not propogate further.
• In a try block, the lines after the line throwing the exception are not executed.
What	
  is	
  the	
  use	
  of	
  finally	
  block	
  in	
  Exception	
  Handling?	
  
When an exception happens, the code after the line throwing exception is not executed. If code for things
like closing a connection is present in these lines of code, it is not executed. This leads to connection and
other resource leaks.
Code written in finally block is executed even when there is an exception.
2	
   Java	
  Interview	
  Questions	
  –	
  www.JavaInterview.in	
   	
  
	
  
Consider the example below. This is code without a finally block . We have Connection class with open
and close methods. An exception happens in the main method. The connection is not closed because
there is no finally block.
	
  
class	
  Connection	
  {	
  
	
  	
  	
  	
  void	
  open()	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  System.out.println("Connection	
  Opened");	
  
	
  	
  	
  	
  }	
  
	
  
	
  	
  	
  	
  void	
  close()	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  System.out.println("Connection	
  Closed");	
  
	
  	
  	
  	
  }	
  
}	
  
	
  
public	
  class	
  ExceptionHandlingExample1	
  {	
  
	
  
	
  	
  	
  	
  public	
  static	
  void	
  main(String[]	
  args)	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  try	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  Connection	
  connection	
  =	
  new	
  Connection();	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  connection.open();	
  
	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  //	
  LOGIC	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  String	
  str	
  =	
  null;	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  str.toString();	
  
	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  connection.close();	
  
	
  	
  	
  	
  	
  	
  	
  	
  }	
  catch	
  (Exception	
  e)	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  //	
  NOT	
  PRINTING	
  EXCEPTION	
  TRACE-­‐	
  BAD	
  PRACTICE	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  System.out.println("Exception	
  Handled	
  -­‐	
  Main");	
  
	
  	
  	
  	
  	
  	
  	
  	
  }	
  
	
  	
  	
  	
  }	
  
}	
  
Output
Connection Opened
Exception Handled - Main
Connection that is opened is not closed. This results in a dangling (un-closed) connection.
Finally block is used when code needs to be executed irrespective of whether an exception is thrown. Let
us now move connection.close(); into a finally block. Also connection declaration is moved out of the try
block to make it visible in the finally block.
	
  	
  	
  	
  public	
  static	
  void	
  main(String[]	
  args)	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  Connection	
  connection	
  =	
  new	
  Connection();	
  
	
  	
  	
  	
  	
  	
  	
  	
  connection.open();	
  
	
  	
  	
  	
  	
  	
  	
  	
  try	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  //	
  LOGIC	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  String	
  str	
  =	
  null;	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  str.toString();	
  
	
  
	
  	
  	
  	
  	
  	
  	
  	
  }	
  catch	
  (Exception	
  e)	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  //	
  NOT	
  PRINTING	
  EXCEPTION	
  TRACE	
  -­‐	
  BAD	
  PRACTICE	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  System.out.println("Exception	
  Handled	
  -­‐	
  Main");	
  
	
  	
  	
  	
  	
  	
  	
  	
  }	
  finally	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  connection.close();	
  
Java	
  Interview	
  Questions	
  –	
  www.JavaInterview.in	
   3	
  
	
  
	
  	
  	
  	
  	
  	
  	
  	
  }	
  
	
  	
  	
  	
  }	
  
Output
Connection Opened
Exception Handled - Main
Connection Closed
Connection is closed even when exception is thrown. This is because connection.close() is called in the
finally block.
Finally block is always executed (even when an exception is thrown). So, if we want some code to be
always executed we can move it to finally block.
	
  
Java	
  Interview	
  Questions	
  –	
  www.JavaInterview.in	
  
At	
  http://www.JavaInterview.in,	
  we	
  want	
  you	
  to	
  clear	
  java	
  interview	
  with	
  ease.	
  So,	
  in	
  addition	
  to	
  
focussing	
  on	
  Core	
  and	
  Advanced	
  Java	
  we	
  also	
  focus	
  on	
  topics	
  like	
  Code	
  Reviews,	
  Performance,	
  	
  Design	
  
Patterns,	
  Spring	
  and	
  Struts.	
  
We	
  have	
  created	
  more	
  than	
  20	
  videos	
  to	
  help	
  you	
  understand	
  these	
  topics	
  and	
  become	
  an	
  expert	
  at	
  
them.	
  Visit	
  our	
  website	
  http://www.JavaInterview.in	
  for	
  complete	
  list	
  of	
  videos.	
  	
  Other	
  than	
  the	
  videos,	
  
we	
  answer	
  the	
  top	
  200	
  frequently	
  asked	
  interview	
  questions	
  on	
  our	
  website.	
  
With	
  more	
  900K	
  video	
  views	
  (Apr	
  2015),	
  we	
  are	
  the	
  most	
  popular	
  channel	
  on	
  Java	
  Interview	
  Questions	
  
on	
  YouTube.	
  
Register	
  here	
  for	
  more	
  updates	
  :	
  https://feedburner.google.com/fb/a/mailverify?uri=RithusTutorials	
  
Java	
  Interview	
  :	
  A	
  Freshers	
  Guide	
  -­‐	
  Part	
  1:	
  https://www.youtube.com/watch?v=njZ48YVkei0	
  
Java	
  Interview	
  :	
  A	
  Freshers	
  Guide	
  -­‐	
  Part	
  2:	
  https://www.youtube.com/watch?v=xyXuo0y-xoU	
  
	
  
In	
  what	
  kind	
  of	
  scenarios,	
  a	
  finally	
  block	
  is	
  not	
  executed?	
  
Code in finally is NOT executed only in two situations.
1. If exception is thrown in finally.
2. If JVM Crashes in between (for example, System.exit()).
Is	
  a	
  finally	
  block	
  executed	
  even	
  when	
  there	
  is	
  a	
  return	
  statement	
  in	
  the	
  try	
  
block?	
  
private	
  static	
  void	
  method2()	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  Connection	
  connection	
  =	
  new	
  Connection();	
  
	
  	
  	
  	
  	
  	
  	
  	
  connection.open();	
  
	
  	
  	
  	
  	
  	
  	
  	
  try	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  //	
  LOGIC	
  	
  	
  	
  	
  
4	
   Java	
  Interview	
  Questions	
  –	
  www.JavaInterview.in	
   	
  
	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  String	
  str	
  =	
  null;	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  str.toString();	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  return;	
  
	
  	
  	
  	
  	
  	
  	
  	
  }	
  catch	
  (Exception	
  e)	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  //	
  NOT	
  PRINTING	
  EXCEPTION	
  TRACE	
  -­‐	
  BAD	
  PRACTICE	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  System.out.println("Exception	
  Handled	
  -­‐	
  Method	
  2");	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  return;	
  
	
  	
  	
  	
  	
  	
  	
  	
  }	
  finally	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  connection.close();	
  
	
  	
  	
  	
  	
  	
  	
  	
  }	
  
	
  	
  	
  	
  }	
  
Is	
  a	
  try	
  block	
  without	
  corresponding	
  catch	
  	
  block	
  allowed?	
  
Yes.	
  try	
  without	
  a	
  catch	
  is	
  allowed.	
  Example	
  below.	
  
private	
  static	
  void	
  method2()	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  Connection	
  connection	
  =	
  new	
  Connection();	
  
	
  	
  	
  	
  	
  	
  	
  	
  connection.open();	
  
	
  	
  	
  	
  	
  	
  	
  	
  try	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  //	
  LOGIC	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  String	
  str	
  =	
  null;	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  str.toString();	
  
	
  	
  	
  	
  	
  	
  	
  	
  }	
  finally	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  connection.close();	
  
	
  	
  	
  	
  	
  	
  	
  	
  }	
  
	
  	
  	
  	
  }	
  
However	
  a	
  try	
  block	
  without	
  both	
  catch	
  and	
  finally	
  is	
  NOT	
  allowed.	
  	
  
Below method would give a Compilation Error!! (End of try block)
	
  	
  	
  	
  private	
  static	
  void	
  method2()	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  Connection	
  connection	
  =	
  new	
  Connection();	
  
	
  	
  	
  	
  	
  	
  	
  	
  connection.open();	
  
	
  	
  	
  	
  	
  	
  	
  	
  try	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  //	
  LOGIC	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  String	
  str	
  =	
  null;	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  str.toString();	
  
	
  	
  	
  	
  	
  	
  	
  	
  }//COMPILER	
  ERROR!!	
  
	
  	
  	
  	
  }	
  
Explain	
  the	
  hierarchy	
  of	
  Exception	
  related	
  classes	
  in	
  Java?	
  
Throwable is the highest level of Error Handling classes.
Below class definitions show the pre-defined exception hierarchy in Java.
//Pre-­‐defined	
  Java	
  Classes	
  
class	
  Error	
  extends	
  Throwable{}	
  
class	
  Exception	
  extends	
  Throwable{}	
  
class	
  RuntimeException	
  extends	
  Exception{}	
  
	
  
Below class definitions show creation of a programmer defined exception in Java.	
  
//Programmer	
  defined	
  classes	
  
class	
  CheckedException1	
  extends	
  Exception{}	
  
Java	
  Interview	
  Questions	
  –	
  www.JavaInterview.in	
   5	
  
	
  
class	
  CheckedException2	
  extends	
  CheckedException1{}	
  
	
  
class	
  UnCheckedException	
  extends	
  RuntimeException{}	
  
class	
  UnCheckedException2	
  extends	
  UnCheckedException{}	
  
What	
  is	
  difference	
  between	
  an	
  Error	
  and	
  an	
  Exception?	
  
Error is used in situations when there is nothing a programmer can do about an error. Ex:
StackOverflowError, OutOfMemoryError. Exception is used when a programmer can handle the
exception.
What	
   is	
   the	
   difference	
   between	
   a	
   	
   Checked	
   Exception	
   and	
   an	
   Un-­‐Checked	
  
Exception?	
  
RuntimeException and classes that extend RuntimeException are called unchecked exceptions. For
Example: RuntimeException,UnCheckedException,UnCheckedException2 are unchecked or RunTime
Exceptions. There are subclasses of RuntimeException (which means they are subclasses of Exception
also.)
Other Exception Classes (which don’t fit the earlier definition). These are also called Checked Exceptions.
Exception, CheckedException1,CheckedException2 are checked exceptions. They are subclasses of
Exception which are not subclasses of RuntimeException.
How	
  do	
  you	
  throw	
  a	
  Checked	
  Exception	
  from	
  a	
  Method?
Consider the example below. The method addAmounts throws a new Exception. However, it gives us a
compilation error because Exception is a Checked Exception.
All classes that are not RuntimeException or subclasses of RuntimeException but extend Exception are
called CheckedExceptions. The rule for CheckedExceptions is that they should be handled or thrown.
Handled means it should be completed handled - i.e. not throw out of the method. Thrown means the
method should declare that it throws the exception
Example	
  without	
  throws:	
  Does	
  NOT	
  compile	
  
class	
  AmountAdder	
  {	
  
	
  	
  	
  	
  static	
  Amount	
  addAmounts(Amount	
  amount1,	
  Amount	
  amount2)	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  if	
  (!amount1.currency.equals(amount2.currency))	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  throw	
   new	
   Exception("Currencies	
   don't	
   match");//	
   COMPILER	
   ERROR!	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  
//	
  Unhandled	
  exception	
  type	
  Exception	
  
	
  	
  	
  	
  	
  	
  	
  	
  }	
  
	
  	
  	
  	
  	
  	
  	
  	
  return	
  new	
  Amount(amount1.currency,	
  amount1.amount	
  +	
  amount2.amount);	
  
	
  	
  	
  	
  }	
  
}	
  
Example	
  with	
  throws	
  definition
Let's look at how to declare throwing an exception from a method.
Look at the line "static Amount addAmounts(Amount amount1, Amount amount2) throws Exception". This
is how we declare that a method throws Exception.
	
  
class	
  AmountAdder	
  {	
  
	
  	
  	
  	
  static	
  Amount	
  addAmounts(Amount	
  amount1,	
  Amount	
  amount2)	
  throws	
  Exception	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  if	
  (!amount1.currency.equals(amount2.currency))	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  throw	
  new	
  Exception("Currencies	
  don't	
  match");	
  
	
  	
  	
  	
  	
  	
  	
  	
  }	
  
	
  	
  	
  	
  	
  	
  	
  	
  return	
  new	
  Amount(amount1.currency,	
  amount1.amount	
  +	
  amount2.amount);	
  
6	
   Java	
  Interview	
  Questions	
  –	
  www.JavaInterview.in	
   	
  
	
  
	
  	
  	
  	
  }	
  
}	
  
How	
  do	
  you	
  create	
  a	
  Custom	
  Exception	
  Classes?	
  
We can create a custom exception by extending Exception class or RuntimeException class. If we extend
Exception class, it will be a checked exception class. If we extend RuntimeException class, then we
create an unchecked exception class.
Example	
  
class	
  CurrenciesDoNotMatchException	
  extends	
  Exception{	
  
}	
  
Let’s now create some sample code to use CurrenciesDoNotMatchException. Since it is a checked
exception we need do two things a. throw	
   new	
   CurrenciesDoNotMatchException();	
   b.	
   throws	
  
CurrenciesDoNotMatchException	
  (in	
  method	
  declaration).	
  
class	
  AmountAdder	
  {	
  
	
  	
  	
  	
  static	
  Amount	
  addAmounts(Amount	
  amount1,	
  Amount	
  amount2)	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  throws	
  CurrenciesDoNotMatchException	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  if	
  (!amount1.currency.equals(amount2.currency))	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  throw	
  new	
  CurrenciesDoNotMatchException();	
  
	
  	
  	
  	
  	
  	
  	
  	
  }	
  
	
  	
  	
  	
  	
  	
  	
  	
  return	
  new	
  Amount(amount1.currency,	
  amount1.amount	
  +	
  amount2.amount);	
  
	
  	
  	
  	
  }	
  
}	
  
How	
  should	
  the	
  Exception	
  catch	
  blocks	
  be	
  ordered	
  ?	
  
Specific Exception catch blocks should be before the catch block for a Generic Exception. For example,
CurrenciesDoNotMatchException should be before Exception. Below code gives a compilation error.
	
  	
  	
  	
  public	
  static	
  void	
  main(String[]	
  args)	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  try	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  AmountAdder.addAmounts(new	
  Amount("RUPEE",	
  5),	
  new	
  Amount("DOLLAR",	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  5));	
  
	
  	
  	
  	
  	
  	
  	
  	
  }	
  catch	
  (Exception	
  e)	
  {	
  //	
  COMPILER	
  ERROR!!	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  System.out.println("Handled	
  Exception");	
  
	
  	
  	
  	
  	
  	
  	
  	
  }	
  catch	
  (CurrenciesDoNotMatchException	
  e)	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  System.out.println("Handled	
  CurrenciesDoNotMatchException");	
  
	
  	
  	
  	
  	
  	
  	
  	
  }	
  
	
  	
  	
  	
  }	
  
Can	
  you	
  explain	
  some	
  Exception	
  Handling	
  Best	
  Practices?	
  
Never Completely Hide Exceptions. At the least log them. printStactTrace method prints the entire stack
trace when an exception occurs. If you handle an exception, it is always a good practice to log the trace.
	
  	
  	
  	
  public	
  static	
  void	
  main(String[]	
  args)	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  try	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  AmountAdder.addAmounts(new	
  Amount("RUPEE",	
  5),	
  new	
  Amount("RUPEE",	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  5));	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  String	
  string	
  =	
  null;	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  string.toString();	
  
	
  	
  	
  	
  	
  	
  	
  	
  }	
  catch	
  (CurrenciesDoNotMatchException	
  e)	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  System.out.println("Handled	
  CurrenciesDoNotMatchException");	
  
Java	
  Interview	
  Questions	
  –	
  www.JavaInterview.in	
   7	
  
	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  e.printStackTrace();	
  
	
  	
  	
  	
  	
  	
  	
  	
  }	
  
	
  	
  	
  	
  }	
  
Videos	
  
We	
  have	
  created	
  more	
  than	
  20	
  videos	
  to	
  help	
  you	
  understand	
  these	
  topics	
  and	
  become	
  an	
  expert	
  at	
  
them.	
  	
  You	
  can	
  watch	
  these	
  videos	
  for	
  free	
  on	
  YouTube.	
  Visit	
  our	
  website	
  http://www.JavaInterview.in	
  
for	
  complete	
  list	
  of	
  videos.	
  We	
  answer	
  the	
  top	
  200	
  frequently	
  asked	
  interview	
  questions	
  on	
  the	
  website.	
  
Register	
  here	
  for	
  more	
  updates	
  :	
  https://feedburner.google.com/fb/a/mailverify?uri=RithusTutorials	
  	
  
Java	
  Interview	
  :	
  A	
  Freshers	
  Guide	
  -­‐	
  Part	
  1:	
  https://www.youtube.com/watch?v=njZ48YVkei0	
  
Java	
  Interview	
  :	
  A	
  Freshers	
  Guide	
  -­‐	
  Part	
  2:	
  https://www.youtube.com/watch?v=xyXuo0y-xoU	
  
Java	
  Interview	
  :	
  A	
  Guide	
  for	
  Experienced:	
  https://www.youtube.com/watch?v=0xcgzUdTO5M
Collections	
  Interview	
  Questions	
  1:	
  https://www.youtube.com/watch?v=GnR4hCvEIJQ
Collections	
  Interview	
  Questions	
  2:	
  https://www.youtube.com/watch?v=6dKGpOKAQqs
Collections	
  Interview	
  Questions	
  3:	
  https://www.youtube.com/watch?v=_JTIYhnLemA
Collections	
  Interview	
  Questions	
  4:	
  https://www.youtube.com/watch?v=ZNhT_Z8_q9s
Collections	
  Interview	
  Questions	
  5:	
  https://www.youtube.com/watch?v=W5c8uXi4qTw
Ad

More Related Content

What's hot (20)

JAVA - Throwable class
JAVA - Throwable classJAVA - Throwable class
JAVA - Throwable class
asifpatel20
 
Java review: try catch
Java review: try catchJava review: try catch
Java review: try catch
Muzahidul Islam
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
kamal kotecha
 
Exceptional Handling in Java
Exceptional Handling in JavaExceptional Handling in Java
Exceptional Handling in Java
QaziUmarF786
 
Types of exceptions
Types of exceptionsTypes of exceptions
Types of exceptions
myrajendra
 
Java - Exception Handling Concepts
Java - Exception Handling ConceptsJava - Exception Handling Concepts
Java - Exception Handling Concepts
Victer Paul
 
Java exception
Java exception Java exception
Java exception
Arati Gadgil
 
Built in exceptions
Built in exceptions Built in exceptions
Built in exceptions
TharuniDiddekunta
 
B.Sc. III(VI Sem) Advance Java Unit1: Exception Handling & Multithreading
B.Sc. III(VI Sem) Advance Java Unit1: Exception Handling & MultithreadingB.Sc. III(VI Sem) Advance Java Unit1: Exception Handling & Multithreading
B.Sc. III(VI Sem) Advance Java Unit1: Exception Handling & Multithreading
Assistant Professor, Shri Shivaji Science College, Amravati
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
Lovely Professional University
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
Ganesh kumar reddy
 
Java exceptions
Java exceptionsJava exceptions
Java exceptions
Pawan Kumar
 
Chap2 exception handling
Chap2 exception handlingChap2 exception handling
Chap2 exception handling
raksharao
 
exception handling in java
exception handling in java exception handling in java
exception handling in java
aptechsravan
 
Exceptionhandling
ExceptionhandlingExceptionhandling
Exceptionhandling
Nuha Noor
 
Exception handling in java
Exception handling  in javaException handling  in java
Exception handling in java
Elizabeth alexander
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-iv
RubaNagarajan
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
lalithambiga kamaraj
 
Nalinee java
Nalinee javaNalinee java
Nalinee java
Nalinee Choudhary
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
ARAFAT ISLAM
 

Similar to Java exception handling (20)

Exception Handling,finally,catch,throw,throws,try.pptx
Exception Handling,finally,catch,throw,throws,try.pptxException Handling,finally,catch,throw,throws,try.pptx
Exception Handling,finally,catch,throw,throws,try.pptx
ArunPatrick2
 
Exception Hnadling java programming language
Exception Hnadling  java programming languageException Hnadling  java programming language
Exception Hnadling java programming language
ushakiranv110
 
Unit 4 exceptions and threads
Unit 4 exceptions and threadsUnit 4 exceptions and threads
Unit 4 exceptions and threads
DevaKumari Vijay
 
presentation-on-exception-handling-160611180456 (1).pptx
presentation-on-exception-handling-160611180456 (1).pptxpresentation-on-exception-handling-160611180456 (1).pptx
presentation-on-exception-handling-160611180456 (1).pptx
ArunPatrick2
 
presentation-on-exception-handling 1.pptx
presentation-on-exception-handling 1.pptxpresentation-on-exception-handling 1.pptx
presentation-on-exception-handling 1.pptx
ArunPatrickK1
 
Java unit3
Java unit3Java unit3
Java unit3
Abhishek Khune
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
gopalrajput11
 
8.Exception handling latest(MB).ppt .
8.Exception handling latest(MB).ppt      .8.Exception handling latest(MB).ppt      .
8.Exception handling latest(MB).ppt .
happycocoman
 
presentation-on-exception-handling-160611180456 (1).pptx
presentation-on-exception-handling-160611180456 (1).pptxpresentation-on-exception-handling-160611180456 (1).pptx
presentation-on-exception-handling-160611180456 (1).pptx
ArunPatrickK1
 
Exceptions handling in java
Exceptions handling in javaExceptions handling in java
Exceptions handling in java
junnubabu
 
7_exception.pdf
7_exception.pdf7_exception.pdf
7_exception.pdf
AyushGaming7
 
Exception handling
Exception handlingException handling
Exception handling
Ardhendu Nandi
 
UNIT 2.pptx
UNIT 2.pptxUNIT 2.pptx
UNIT 2.pptx
EduclentMegasoftel
 
Exception handling in java.pptx
Exception handling in java.pptxException handling in java.pptx
Exception handling in java.pptx
Nagaraju Pamarthi
 
JAVA PPT -4 BY ADI.pdf
JAVA PPT -4 BY ADI.pdfJAVA PPT -4 BY ADI.pdf
JAVA PPT -4 BY ADI.pdf
Prof. Dr. K. Adisesha
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
Garuda Trainings
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
pooja kumari
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
pooja kumari
 
Exception handling, Stream Classes, Multithread Programming
Exception handling, Stream Classes, Multithread ProgrammingException handling, Stream Classes, Multithread Programming
Exception handling, Stream Classes, Multithread Programming
Prabu U
 
Unit-4 Java ppt for BCA Students Madras Univ
Unit-4 Java ppt for BCA Students Madras UnivUnit-4 Java ppt for BCA Students Madras Univ
Unit-4 Java ppt for BCA Students Madras Univ
lavanyasujat1
 
Exception Handling,finally,catch,throw,throws,try.pptx
Exception Handling,finally,catch,throw,throws,try.pptxException Handling,finally,catch,throw,throws,try.pptx
Exception Handling,finally,catch,throw,throws,try.pptx
ArunPatrick2
 
Exception Hnadling java programming language
Exception Hnadling  java programming languageException Hnadling  java programming language
Exception Hnadling java programming language
ushakiranv110
 
Unit 4 exceptions and threads
Unit 4 exceptions and threadsUnit 4 exceptions and threads
Unit 4 exceptions and threads
DevaKumari Vijay
 
presentation-on-exception-handling-160611180456 (1).pptx
presentation-on-exception-handling-160611180456 (1).pptxpresentation-on-exception-handling-160611180456 (1).pptx
presentation-on-exception-handling-160611180456 (1).pptx
ArunPatrick2
 
presentation-on-exception-handling 1.pptx
presentation-on-exception-handling 1.pptxpresentation-on-exception-handling 1.pptx
presentation-on-exception-handling 1.pptx
ArunPatrickK1
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
gopalrajput11
 
8.Exception handling latest(MB).ppt .
8.Exception handling latest(MB).ppt      .8.Exception handling latest(MB).ppt      .
8.Exception handling latest(MB).ppt .
happycocoman
 
presentation-on-exception-handling-160611180456 (1).pptx
presentation-on-exception-handling-160611180456 (1).pptxpresentation-on-exception-handling-160611180456 (1).pptx
presentation-on-exception-handling-160611180456 (1).pptx
ArunPatrickK1
 
Exceptions handling in java
Exceptions handling in javaExceptions handling in java
Exceptions handling in java
junnubabu
 
Exception handling in java.pptx
Exception handling in java.pptxException handling in java.pptx
Exception handling in java.pptx
Nagaraju Pamarthi
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
pooja kumari
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
pooja kumari
 
Exception handling, Stream Classes, Multithread Programming
Exception handling, Stream Classes, Multithread ProgrammingException handling, Stream Classes, Multithread Programming
Exception handling, Stream Classes, Multithread Programming
Prabu U
 
Unit-4 Java ppt for BCA Students Madras Univ
Unit-4 Java ppt for BCA Students Madras UnivUnit-4 Java ppt for BCA Students Madras Univ
Unit-4 Java ppt for BCA Students Madras Univ
lavanyasujat1
 
Ad

Recently uploaded (20)

Biophysics Chapter 3 Methods of Studying Macromolecules.pdf
Biophysics Chapter 3 Methods of Studying Macromolecules.pdfBiophysics Chapter 3 Methods of Studying Macromolecules.pdf
Biophysics Chapter 3 Methods of Studying Macromolecules.pdf
PKLI-Institute of Nursing and Allied Health Sciences Lahore , Pakistan.
 
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - WorksheetCBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
Sritoma Majumder
 
apa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdfapa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdf
Ishika Ghosh
 
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
larencebapu132
 
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
Celine George
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 4-30-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 4-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-30-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
Introduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe EngineeringIntroduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe Engineering
Damian T. Gordon
 
Political History of Pala dynasty Pala Rulers NEP.pptx
Political History of Pala dynasty Pala Rulers NEP.pptxPolitical History of Pala dynasty Pala Rulers NEP.pptx
Political History of Pala dynasty Pala Rulers NEP.pptx
Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
Grade 3 - English - Printable Worksheet (PDF Format)
Grade 3 - English - Printable Worksheet  (PDF Format)Grade 3 - English - Printable Worksheet  (PDF Format)
Grade 3 - English - Printable Worksheet (PDF Format)
Sritoma Majumder
 
dynastic art of the Pallava dynasty south India
dynastic art of the Pallava dynasty south Indiadynastic art of the Pallava dynasty south India
dynastic art of the Pallava dynasty south India
PrachiSontakke5
 
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptxSCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
Ronisha Das
 
How to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odooHow to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odoo
Celine George
 
Sugar-Sensing Mechanism in plants....pptx
Sugar-Sensing Mechanism in plants....pptxSugar-Sensing Mechanism in plants....pptx
Sugar-Sensing Mechanism in plants....pptx
Dr. Renu Jangid
 
Understanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s GuideUnderstanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s Guide
GS Virdi
 
Exercise Physiology MCQS By DR. NASIR MUSTAFA
Exercise Physiology MCQS By DR. NASIR MUSTAFAExercise Physiology MCQS By DR. NASIR MUSTAFA
Exercise Physiology MCQS By DR. NASIR MUSTAFA
Dr. Nasir Mustafa
 
Contact Lens:::: An Overview.pptx.: Optometry
Contact Lens:::: An Overview.pptx.: OptometryContact Lens:::: An Overview.pptx.: Optometry
Contact Lens:::: An Overview.pptx.: Optometry
MushahidRaza8
 
"Basics of Heterocyclic Compounds and Their Naming Rules"
"Basics of Heterocyclic Compounds and Their Naming Rules""Basics of Heterocyclic Compounds and Their Naming Rules"
"Basics of Heterocyclic Compounds and Their Naming Rules"
rupalinirmalbpharm
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulsepulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
sushreesangita003
 
How to Manage Purchase Alternatives in Odoo 18
How to Manage Purchase Alternatives in Odoo 18How to Manage Purchase Alternatives in Odoo 18
How to Manage Purchase Alternatives in Odoo 18
Celine George
 
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - WorksheetCBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
Sritoma Majumder
 
apa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdfapa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdf
Ishika Ghosh
 
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
larencebapu132
 
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
Celine George
 
Introduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe EngineeringIntroduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe Engineering
Damian T. Gordon
 
Grade 3 - English - Printable Worksheet (PDF Format)
Grade 3 - English - Printable Worksheet  (PDF Format)Grade 3 - English - Printable Worksheet  (PDF Format)
Grade 3 - English - Printable Worksheet (PDF Format)
Sritoma Majumder
 
dynastic art of the Pallava dynasty south India
dynastic art of the Pallava dynasty south Indiadynastic art of the Pallava dynasty south India
dynastic art of the Pallava dynasty south India
PrachiSontakke5
 
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptxSCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
Ronisha Das
 
How to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odooHow to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odoo
Celine George
 
Sugar-Sensing Mechanism in plants....pptx
Sugar-Sensing Mechanism in plants....pptxSugar-Sensing Mechanism in plants....pptx
Sugar-Sensing Mechanism in plants....pptx
Dr. Renu Jangid
 
Understanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s GuideUnderstanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s Guide
GS Virdi
 
Exercise Physiology MCQS By DR. NASIR MUSTAFA
Exercise Physiology MCQS By DR. NASIR MUSTAFAExercise Physiology MCQS By DR. NASIR MUSTAFA
Exercise Physiology MCQS By DR. NASIR MUSTAFA
Dr. Nasir Mustafa
 
Contact Lens:::: An Overview.pptx.: Optometry
Contact Lens:::: An Overview.pptx.: OptometryContact Lens:::: An Overview.pptx.: Optometry
Contact Lens:::: An Overview.pptx.: Optometry
MushahidRaza8
 
"Basics of Heterocyclic Compounds and Their Naming Rules"
"Basics of Heterocyclic Compounds and Their Naming Rules""Basics of Heterocyclic Compounds and Their Naming Rules"
"Basics of Heterocyclic Compounds and Their Naming Rules"
rupalinirmalbpharm
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulsepulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
sushreesangita003
 
How to Manage Purchase Alternatives in Odoo 18
How to Manage Purchase Alternatives in Odoo 18How to Manage Purchase Alternatives in Odoo 18
How to Manage Purchase Alternatives in Odoo 18
Celine George
 
Ad

Java exception handling

  • 1. Java  Interview  Questions  –  www.JavaInterview.in   1     Exception  Handling   Explain  about  Exception  Handling  with  an  example.   Exception Handling helps us to recover from an unexpected situations – File not found or network connection is down. The important part in exception handling is the try – catch block. Look at the example below.        public  static  void  main(String[]  args)  {                  method1();                  System.out.println("Line  after  Exception  -­‐  Main");          }            private  static  void  method1()  {                  method2();                  System.out.println("Line  after  Exception  -­‐  Method  1");          }            private  static  void  method2()  {                  try  {                          String  str  =  null;                          str.toString();                          System.out.println("Line  after  Exception  -­‐  Method  2");                  }  catch  (Exception  e)  {                          //  NOT  PRINTING  EXCEPTION  TRACE-­‐  BAD  PRACTICE                          System.out.println("Exception  Handled  -­‐  Method  2");                  }          }   Program  Output   Exception Handled - Method 2 Line after Exception - Method 1 Line after Exception - Main When exception is handled in a method, the calling methods will not need worry about that exception. Since Exception Handling is added in the method method2, the exception did not propogate to method1 i.e. method1 does not know about the exception in method2. Few important things to remember from this example. • If exception is handled, it does not propogate further. • In a try block, the lines after the line throwing the exception are not executed. What  is  the  use  of  finally  block  in  Exception  Handling?   When an exception happens, the code after the line throwing exception is not executed. If code for things like closing a connection is present in these lines of code, it is not executed. This leads to connection and other resource leaks. Code written in finally block is executed even when there is an exception.
  • 2. 2   Java  Interview  Questions  –  www.JavaInterview.in       Consider the example below. This is code without a finally block . We have Connection class with open and close methods. An exception happens in the main method. The connection is not closed because there is no finally block.   class  Connection  {          void  open()  {                  System.out.println("Connection  Opened");          }            void  close()  {                  System.out.println("Connection  Closed");          }   }     public  class  ExceptionHandlingExample1  {            public  static  void  main(String[]  args)  {                  try  {                          Connection  connection  =  new  Connection();                          connection.open();                            //  LOGIC                          String  str  =  null;                          str.toString();                            connection.close();                  }  catch  (Exception  e)  {                          //  NOT  PRINTING  EXCEPTION  TRACE-­‐  BAD  PRACTICE                          System.out.println("Exception  Handled  -­‐  Main");                  }          }   }   Output Connection Opened Exception Handled - Main Connection that is opened is not closed. This results in a dangling (un-closed) connection. Finally block is used when code needs to be executed irrespective of whether an exception is thrown. Let us now move connection.close(); into a finally block. Also connection declaration is moved out of the try block to make it visible in the finally block.        public  static  void  main(String[]  args)  {                  Connection  connection  =  new  Connection();                  connection.open();                  try  {                          //  LOGIC                          String  str  =  null;                          str.toString();                    }  catch  (Exception  e)  {                          //  NOT  PRINTING  EXCEPTION  TRACE  -­‐  BAD  PRACTICE                          System.out.println("Exception  Handled  -­‐  Main");                  }  finally  {                          connection.close();  
  • 3. Java  Interview  Questions  –  www.JavaInterview.in   3                    }          }   Output Connection Opened Exception Handled - Main Connection Closed Connection is closed even when exception is thrown. This is because connection.close() is called in the finally block. Finally block is always executed (even when an exception is thrown). So, if we want some code to be always executed we can move it to finally block.   Java  Interview  Questions  –  www.JavaInterview.in   At  http://www.JavaInterview.in,  we  want  you  to  clear  java  interview  with  ease.  So,  in  addition  to   focussing  on  Core  and  Advanced  Java  we  also  focus  on  topics  like  Code  Reviews,  Performance,    Design   Patterns,  Spring  and  Struts.   We  have  created  more  than  20  videos  to  help  you  understand  these  topics  and  become  an  expert  at   them.  Visit  our  website  http://www.JavaInterview.in  for  complete  list  of  videos.    Other  than  the  videos,   we  answer  the  top  200  frequently  asked  interview  questions  on  our  website.   With  more  900K  video  views  (Apr  2015),  we  are  the  most  popular  channel  on  Java  Interview  Questions   on  YouTube.   Register  here  for  more  updates  :  https://feedburner.google.com/fb/a/mailverify?uri=RithusTutorials   Java  Interview  :  A  Freshers  Guide  -­‐  Part  1:  https://www.youtube.com/watch?v=njZ48YVkei0   Java  Interview  :  A  Freshers  Guide  -­‐  Part  2:  https://www.youtube.com/watch?v=xyXuo0y-xoU     In  what  kind  of  scenarios,  a  finally  block  is  not  executed?   Code in finally is NOT executed only in two situations. 1. If exception is thrown in finally. 2. If JVM Crashes in between (for example, System.exit()). Is  a  finally  block  executed  even  when  there  is  a  return  statement  in  the  try   block?   private  static  void  method2()  {                  Connection  connection  =  new  Connection();                  connection.open();                  try  {                          //  LOGIC          
  • 4. 4   Java  Interview  Questions  –  www.JavaInterview.in                              String  str  =  null;                          str.toString();                          return;                  }  catch  (Exception  e)  {                          //  NOT  PRINTING  EXCEPTION  TRACE  -­‐  BAD  PRACTICE                          System.out.println("Exception  Handled  -­‐  Method  2");                          return;                  }  finally  {                          connection.close();                  }          }   Is  a  try  block  without  corresponding  catch    block  allowed?   Yes.  try  without  a  catch  is  allowed.  Example  below.   private  static  void  method2()  {                  Connection  connection  =  new  Connection();                  connection.open();                  try  {                          //  LOGIC                          String  str  =  null;                          str.toString();                  }  finally  {                          connection.close();                  }          }   However  a  try  block  without  both  catch  and  finally  is  NOT  allowed.     Below method would give a Compilation Error!! (End of try block)        private  static  void  method2()  {                  Connection  connection  =  new  Connection();                  connection.open();                  try  {                          //  LOGIC                          String  str  =  null;                          str.toString();                  }//COMPILER  ERROR!!          }   Explain  the  hierarchy  of  Exception  related  classes  in  Java?   Throwable is the highest level of Error Handling classes. Below class definitions show the pre-defined exception hierarchy in Java. //Pre-­‐defined  Java  Classes   class  Error  extends  Throwable{}   class  Exception  extends  Throwable{}   class  RuntimeException  extends  Exception{}     Below class definitions show creation of a programmer defined exception in Java.   //Programmer  defined  classes   class  CheckedException1  extends  Exception{}  
  • 5. Java  Interview  Questions  –  www.JavaInterview.in   5     class  CheckedException2  extends  CheckedException1{}     class  UnCheckedException  extends  RuntimeException{}   class  UnCheckedException2  extends  UnCheckedException{}   What  is  difference  between  an  Error  and  an  Exception?   Error is used in situations when there is nothing a programmer can do about an error. Ex: StackOverflowError, OutOfMemoryError. Exception is used when a programmer can handle the exception. What   is   the   difference   between   a     Checked   Exception   and   an   Un-­‐Checked   Exception?   RuntimeException and classes that extend RuntimeException are called unchecked exceptions. For Example: RuntimeException,UnCheckedException,UnCheckedException2 are unchecked or RunTime Exceptions. There are subclasses of RuntimeException (which means they are subclasses of Exception also.) Other Exception Classes (which don’t fit the earlier definition). These are also called Checked Exceptions. Exception, CheckedException1,CheckedException2 are checked exceptions. They are subclasses of Exception which are not subclasses of RuntimeException. How  do  you  throw  a  Checked  Exception  from  a  Method? Consider the example below. The method addAmounts throws a new Exception. However, it gives us a compilation error because Exception is a Checked Exception. All classes that are not RuntimeException or subclasses of RuntimeException but extend Exception are called CheckedExceptions. The rule for CheckedExceptions is that they should be handled or thrown. Handled means it should be completed handled - i.e. not throw out of the method. Thrown means the method should declare that it throws the exception Example  without  throws:  Does  NOT  compile   class  AmountAdder  {          static  Amount  addAmounts(Amount  amount1,  Amount  amount2)  {                  if  (!amount1.currency.equals(amount2.currency))  {                          throw   new   Exception("Currencies   don't   match");//   COMPILER   ERROR!                             //  Unhandled  exception  type  Exception                  }                  return  new  Amount(amount1.currency,  amount1.amount  +  amount2.amount);          }   }   Example  with  throws  definition Let's look at how to declare throwing an exception from a method. Look at the line "static Amount addAmounts(Amount amount1, Amount amount2) throws Exception". This is how we declare that a method throws Exception.   class  AmountAdder  {          static  Amount  addAmounts(Amount  amount1,  Amount  amount2)  throws  Exception  {                  if  (!amount1.currency.equals(amount2.currency))  {                          throw  new  Exception("Currencies  don't  match");                  }                  return  new  Amount(amount1.currency,  amount1.amount  +  amount2.amount);  
  • 6. 6   Java  Interview  Questions  –  www.JavaInterview.in              }   }   How  do  you  create  a  Custom  Exception  Classes?   We can create a custom exception by extending Exception class or RuntimeException class. If we extend Exception class, it will be a checked exception class. If we extend RuntimeException class, then we create an unchecked exception class. Example   class  CurrenciesDoNotMatchException  extends  Exception{   }   Let’s now create some sample code to use CurrenciesDoNotMatchException. Since it is a checked exception we need do two things a. throw   new   CurrenciesDoNotMatchException();   b.   throws   CurrenciesDoNotMatchException  (in  method  declaration).   class  AmountAdder  {          static  Amount  addAmounts(Amount  amount1,  Amount  amount2)                          throws  CurrenciesDoNotMatchException  {                  if  (!amount1.currency.equals(amount2.currency))  {                          throw  new  CurrenciesDoNotMatchException();                  }                  return  new  Amount(amount1.currency,  amount1.amount  +  amount2.amount);          }   }   How  should  the  Exception  catch  blocks  be  ordered  ?   Specific Exception catch blocks should be before the catch block for a Generic Exception. For example, CurrenciesDoNotMatchException should be before Exception. Below code gives a compilation error.        public  static  void  main(String[]  args)  {                  try  {                          AmountAdder.addAmounts(new  Amount("RUPEE",  5),  new  Amount("DOLLAR",                                          5));                  }  catch  (Exception  e)  {  //  COMPILER  ERROR!!                          System.out.println("Handled  Exception");                  }  catch  (CurrenciesDoNotMatchException  e)  {                          System.out.println("Handled  CurrenciesDoNotMatchException");                  }          }   Can  you  explain  some  Exception  Handling  Best  Practices?   Never Completely Hide Exceptions. At the least log them. printStactTrace method prints the entire stack trace when an exception occurs. If you handle an exception, it is always a good practice to log the trace.        public  static  void  main(String[]  args)  {                  try  {                          AmountAdder.addAmounts(new  Amount("RUPEE",  5),  new  Amount("RUPEE",                                          5));                          String  string  =  null;                          string.toString();                  }  catch  (CurrenciesDoNotMatchException  e)  {                          System.out.println("Handled  CurrenciesDoNotMatchException");  
  • 7. Java  Interview  Questions  –  www.JavaInterview.in   7                            e.printStackTrace();                  }          }   Videos   We  have  created  more  than  20  videos  to  help  you  understand  these  topics  and  become  an  expert  at   them.    You  can  watch  these  videos  for  free  on  YouTube.  Visit  our  website  http://www.JavaInterview.in   for  complete  list  of  videos.  We  answer  the  top  200  frequently  asked  interview  questions  on  the  website.   Register  here  for  more  updates  :  https://feedburner.google.com/fb/a/mailverify?uri=RithusTutorials     Java  Interview  :  A  Freshers  Guide  -­‐  Part  1:  https://www.youtube.com/watch?v=njZ48YVkei0   Java  Interview  :  A  Freshers  Guide  -­‐  Part  2:  https://www.youtube.com/watch?v=xyXuo0y-xoU   Java  Interview  :  A  Guide  for  Experienced:  https://www.youtube.com/watch?v=0xcgzUdTO5M Collections  Interview  Questions  1:  https://www.youtube.com/watch?v=GnR4hCvEIJQ Collections  Interview  Questions  2:  https://www.youtube.com/watch?v=6dKGpOKAQqs Collections  Interview  Questions  3:  https://www.youtube.com/watch?v=_JTIYhnLemA Collections  Interview  Questions  4:  https://www.youtube.com/watch?v=ZNhT_Z8_q9s Collections  Interview  Questions  5:  https://www.youtube.com/watch?v=W5c8uXi4qTw