Monday, December 4, 2017

Interview -Exceptions !



Q #32) What are the types of Exceptions?
Ans: Two types of Exceptions are explained below in detail.
Checked Exception:
These exceptions are checked by the compiler at the time of compilation. Classes that extend Throwable class except Runtime exception and Error are called checked Exception.
Checked Exceptions must either declare the exception using throes keyword (or) surrounded by appropriate try/catch.
E.g. ClassNotFound Exception
Unchecked Exception:
These exceptions are not checked during the compile time by the compiler.  The compiler doesn’t force to handle these exceptions.
It includes:
  • Arithmetic Exception
  • ArrayIndexOutOfBounds Exception
Q #33) What are the different ways to handle exceptions?
Ans: Two different ways to handle exception are explained below:
#1) Using try/catch:
A risky code is surrounded by try block. If an exception occurs, then it is caught by the catch block which is followed by the try block.
Example:
1class Manipulation{
2public static void main(String[] args){
3add();
4}
5Public void add(){
6try{
7addition();
8}catch(Exception e){
9e.printStacktrace();
10}
11}
12}
#2) By declaring throws keyword:
At the end of the method, we can declare the exception using throws keyword.
Example:
1class Manipulation{
2public static void main(String[] args){
3add();
4}
5public void add() throws Exception{
6addition();
7}
8}
Q #34) What are the Advantages of Exception handling?
Ans: Given below are the advantages:
  • The normal flow of the execution won’t be terminated if exception got handled
  • We can identify the problem by using catch declaration
 Q #35) What are Exception handling keywords in Java?
Ans: Given below are the two Exception Handling Keywords:
try:
When a risky code is surrounded by a try block. An exception occurring in the try block is caught by a catch block. Try can be followed either by catch (or) finally (or) both. But any one of the blocks is mandatory.
catch:
This is followed by try block. Exceptions are caught here.
finally:
This is followed either by try block (or) catch block. This block gets executed regardless of an exception. So generally clean up codes are provided here.
Q #36) Explain about Exception Propagation.
Ans: Exception is first thrown from the method which is at the top of the stack. If it doesn’t catch, then it pops up the method and moves to the previous method and so on until they are got.
This is called Exception propagation.
Example:
1public class Manipulation{
2public static void main(String[] args){
3add();
4}
5public void add(){
6addition();
7}
From the above example, the stack looks like as shown below:
Stack Example           
If an exception occurred in the addition() method is not caught, then it moves to the method add(). Then it is moved to the main() method and then it will stop the flow of execution. It is called Exception Propagation.
Q #37) What is the final keyword in Java?
Ans:
Final variable:
Once a variable is declared as final, then the value of the variable could not be changed. It is like a constant.
Example:
final int = 12;
Final method:
A final keyword in a method that couldn’t be overridden. If a method is marked as a final, then it can’t be overridden by the subclass.
Final class:
If a class is declared as final, then the class couldn’t be subclassed. No class can extend the final class.



Question 1: What are the top 10 exceptions faced in production environments across the globe ? What measures have you tab=ken to ensure ,you don't across such exceptions?



-->
1. NullPointerException – 70% of Production Environments
2. NumberFormatException – 55% of Production Environments In at #2 is the NumberFormatException which happens when you try to convert a string to a numeric value and the String is not formatted correctly. It extends IllegalArgumentException which also makes an appearance here at #3.

One easy fix to make sure that the input you’re passing to the parse method passes these regular expression:

For integer values: “-?\\d+”
For float values: “-?\\d+.\\d+”

3. IllegalArgumentException – 50% of Production Environments IllegalArgumentException, appearing at the top 10 exceptions in 50% of the production environments in this survey.

An IllegalArgumentException actually saves you from trouble, and thrown when you’re
passing arguments from an unexpected type to your methods. For example, some method that expects type X and you’re calling it with type Y as an argument. Once again, an error that’s caused by not checking what you’re sending out as input to other methods.
5. IllegalStateException – 22% of Production Environments An IllegalStateException is thrown when you’re trying to use a method in an inappropriate time, like… this scene with Ted and Robin in the first episode of 
NoSuchMethodException – 16% of Production Environments 16% of the production environments in this data crunch had NoSuchMethodException in their top 10.

Since most of us don’t write code while drunk, at least during day time, this doesn’t necessarily mean that we’re that delirious to think we’re seeing something that’s not there. That way the compiler would have caught that way earlier in the process.

This exception is thrown when you’re trying to use a method that doesn’t exist, which happens
when you’re using reflection and getting the method name from some variable or when you’re building against a version of a class and using a different one at production
ClassCastException – 15% of Production Environments

A ClassCastException occurs when we’re trying to cast a class to another class of which it is not an instance. 15% of production environments have it in their top 10 exceptions, quite troublesome.
ParseException – 13% of Production Environments Parsing errors strike again! Whenever we’re passing a string to parse into something else, and it’s not formatted the way it’s supposed to, we’re hit by a ParseException. Bummer.

It’s more common than you might have thought with 13% of the production environments tested in this posted featuring this exception in their top 10.

The solution is… yet again, check yo’ self.
InvocationTargetException – 13% of Production Environments

Another exception that’s thrown at us from the world of Java Reflection is the InvocationTargetException. This one is actually a wrapper, if something goes wrong in an invoked method, that exception is then wrapped with an InvocationTargetException.



Question 1: What are the amendments introduced in exception handling in Java 7 ? How did you incorporate in your application?

1.try with resources











2.Created exception handling design pattern using rethrow clause


2.Clubbed multiple exceptions into common blocks



-->Question 3:What is an exception?

AN ABORNMAL EVENT WHILE EXECUTION OF CODE,IF NOT HANDLED ,WILL PROPOGATE TO JVM,EVENTUALLY RESULTIING IN TERMINATION OF PROGRAM
ü  CHECKED
UNCHECKED

ü  Exception is an abnormal event occurring in execution if program. It can be handled
ü  Error is also an exception condition occurrence, it can not be handled
-->
ü  stackOverflow|outofmemory|linkageError|

Question 4: Types of Errors

UnsupportedClassVersionError – occurs when the JVM attempts to read a class file and determines that the version in the file is not supported, normally because the file was generated with a newer version of Java

StackOverflowError – occurs when the stack space for a thread has run out, typically because an application recurses too deeply
ExceptionInInitializerError – signals that an unexpected exception occurred during the evaluation of a static initializer

OutOfMemoryError – thrown when the JVM cannot allocate more objects because it is out memory, and the garbage collector was unable to make more available

-->
NoClassDefFoundError – is thrown when the classloader tries to load the definition of a class and couldn’t find it, usually because the required class files were not found in the classpath



Question 5:What is a stacktrace and how does it relate to an exception?

-->
-->
Stacktrace provides list of classes and methods that were called,from start  of application to the point of exception occurred.


Question 6:What are the rules we need to follow when overriding a method that throws an exception?



-->

Question 7:List some commonly used Exception methods
ü  getMessage()
ü  printStackTrace()
ü  getLocalizedMessage()
ü  synchronized Throwable getClause
-->
ü  toString()
Question 8:Provide some Java Exception Handling Best Practices?

1)   USE SPECIFIC EXCEPTION INSTEAD OF BASE EXCEPTION
2)   THROW EARLY OR FAIL FAST
3)   CATCH LATER
4)    USE TRY RESOUCES FOR CLEANER CODE
5)   TRY TO USED SINGLE CATCH BLOCK FOR MULTIPLE EXCEPTION
6)   USE CUSTOM EXCEPTIONS
7)   USE EXCEPTIONS JUDICOUSLY
ALWAYS END YOUR CUSTOM EXCEPTION WITH KEYWORD EXCEPTION

-->



Question 9: List some of common exceptions.Please highlight checked in blue & unchecked in red

java.lang
1.     ArithmeticException
2.     ArrayIndexOutOfBoundsException
3.    ArrayStoreException
4.     ClassCastException
5.     ClassNotFoundException
6.     CloneNotSupportedException
7.     IllegalAccessException
8.    IllegalArgumentException
9.     IllegalMonitorStateException
10.  IllegalStateException
11.  IllegalThreadStateException
12.  IndexOutOfBoundsException
13. InstantiationException
14.  InterruptedException
15.  NegativeArraySizeException
16.  NoSuchFieldException
17.  NoSuchMethodException
18. NullPointerException
19.  NumberFormatException
20.  RuntimeException
21.  SecurityException
22.  StringIndexOutOfBoundsException
23. UnsupportedOperationException
java.io
1.     CharConversionException

2.     EOFException
3.    FileNotFoundException
4.     InterruptedIOException
5.     InvalidClassException
6.     InvalidObjectException
7.     IOException
8.    NotActiveException
9.     NotSerializableException
10.  ObjectStreamException
11.  OptionalDataException
12.  StreamCorruptedException
13. SyncFailedException
14.  UnsupportedEncodingException
15.  UTFDataFormatException
16.  WriteAbortedException

java.util
1.     ConcurrentModificationException
2.     EmptyStackException
3.    MissingResourceException
4.     NoSuchElementException
5.     TooManyListenersException

java.security
1.     AccessControlException
2.     DigestException
3.    GeneralSecurityException
4.     InvalidAlgorithmParameterException
5.     InvalidKeyException
6.     InvalidParameterException
7.     KeyException
8.    KeyManagementException
9.     KeyStoreException
10.  NoSuchAlgorithmException
11.  NoSuchProviderException
12.  PrivilegedActionException
13. ProviderException
14.  SignatureException
15.  UnrecoverableKeyException

java.net
1.     BindException
2.     ConnectException
3.    MalformedURLException
4.     NoRouteToHostException
5.     PortUnreachableException
6.     ProtocolException
7.     SocketException
8.    SocketTimeoutException
9.     UnknownHostException :Thrown to indicate that the IP address of a host could not be determined.
10.  UnknownServiceException
-->
11.  URISyntaxException
-->

No comments:

Post a Comment