What are different types of Exceptions?.

Answers were Sorted based on User's Feedback



What are different types of Exceptions?...

Answer / ranganathkini

There are three main types of Exceptions:

1. Checked execptions: which have to be handled by the code.
These represent avoidable exceptional conditions which can
be handled and recovered from.

2. Runtime Exceptions: which need not be handled by the
code. These represent unexpected exceptional conditions
which can be handled but not necessarily recover from.

3. Errors: which need not be handled by the code. These
represent severe unexpected exceptional conditions which
shud not be attempted to handle.

Is This Answer Correct ?    79 Yes 22 No

What are different types of Exceptions?...

Answer / shankar shinde

Checked and UnChecked Exception.

Is This Answer Correct ?    26 Yes 15 No

What are different types of Exceptions?...

Answer / manikandan

EXCEPTION

An Exception is an abnormal condition that arises in a code
sequence at run time, ie.run-time error.

A java Exception is an object that describes an exceptional
condition that has occurred in a piece of code.

When an exceptional condition arises, an object representing
that exception is created and thrown in the method that
caused the error.

Method may choose to handle the exception itself or pass it on.

<--------General for of an exception-handling block------>

try
{
// block of code to monitor for errors
}

catch (ExceptionType1 exOb)
{
// exception handler for ExceptionType1
}

catch (ExceptionType2 exOb)
{
// exception handler for ExceptionType2
}

finally
{
// block of code to be executed before try block ends
}

<-------------Exception Types---------------->

All Exception types are subclasses of the built-in class
Throwable.

Two subclasses

Exception

Error

Exception is used for exceptional conditions that user
program should catch.

You subclass this class to create your own custom exception
types

Important subclass of Exception is RuntimeException.

<----------------EX1: Uncaught Exception------------------->

class Exc0
{
public static void main (String args[])
{
int d = 0;
int a = 42 / d;
}
}

This ex throws Exception such as

java.lang.ArithmeticException: / by zero

at Exc0.main(Exc0.java:4)

Must be caught and dealt with immediately.

<------ catch Exception as in this example--------->

class Exc2
{
public static void main (String args[])
{
int d, a;
try
{
d = 0;
a = 42 / d;
System.out.println ("This will not be printed");
}
catch (ArithmeticException e)
{
System.out.println ("Division by zero.");
}
System.out.println ("After catch statement.");
}
}

OUTPUT

Division by zero.

After catch statement.

Catch is not called, so control never returns to the try block.

You can describe the Exception by passing it as an argument
to println() statement.

Multiple catch clauses

Each catch statement is inspected in order they are specified.

The first one that matches the type of exception is executed.

Others are bypassed.

Execution continues after try/catch block.

class MultiCatch {

public static void main (String args[]) {

try {

int a = args.length;

System.out.println("a = " + a);

int b = 42 / a ;

int c[] ={ 1 };

c[42] = 99;

}catch (ArithmeticException e) {

System.out.println ("Divide by 0:" + e);

} catch (ArrayIndexOutOfBoundsException e) {

System.out.println ("Array Index oob:" + e);

}

System.out.println ("After try/catch blocks.");

}

}

subclasses must come before their superclasses.

In java, unreachable code is an error.

Nested try Statements

Class NestTry {

public static void main (String args[]) {

try {

//….

//….

try {

//…

//….

}catch (ExceptionType exOb) {

//….

}

}catch (ExceptionType exOb) {

//….

}

}

}

Each time a try block is entered, the context of that
exception is pushed n the stack.

If an inner try statement does not have a catch handler for
a particular exception, the stack is unwounded and next try
statement’s catch handlers are inspected for a match.

Continues till 1 catch statement succeeds, or until all try
statements are exhausted.

If no catch statement matches, then the Java run-time will
handle the exception.



Throw

Possible for program to explicitly throw exception

throw ThrowableInstance

ThrowableInstance must be an object of type Throwable or a
subclass of Throwable.

2 ways to obtain Throwable object:

Using a parameter into a catch clause

Creating one with a new operator.

try {

throw new NullPointerException("created");

}catch (NullPointerException e) {

throw e; //rethrow the Exception

}



throws

If a method is capable of causing an exception that it does
not handle, it must specify this behaviour so that callers
of the method can guard themselves against that exception.

type method-name(paramlist) throws exception-list

{

//…..

}

throws clause lists the types of exceptions that a method
might throw.

Necessary for all exceptions, except those of type Error or
RuntimeException, or any of their subclasses.

finally

Whenexceptions are thrown, execution in the method takes
rather abrupt, nonlinear path that alters the normal flow
through the method.

finally creates a block of code that will be executed after
try/catch block has completed and before the code following
try/catch block.

Will execute whether or not the exception is thrown.

Can be useful for closing file handles and freeing up any
other resources that might have been allocated at the
beginning of the method with the intent of disposing of them
before returning.


java’ Biult-in Exceptions

java.lang defines several exception classes.

Checked and Unchecked Exceptions

java.lang implicitly imported.

So, most Exceptions derived from RuntimeException are
automatically available.

They need not be specified in a methods throws list.

Are called unchecked Exceptions, as compiler does not check
to see if a method handles or throws these exceptions.

Unchecked RuntimeException Subclasses

ArithmeticException

ArrayIndexOutOfBoundsException

ArraStoreException

ClassCastException

IllegalArgumentException

IllegalMonitorStateException

IllegalStateException

IllegalThreadStateException

IndexOutOfBoundsException

NegativeArraySizeException

NullPointerException

NumberFormatException

SecurityException

StringIndexOutOfBounds

UnsupportedOperationException



Java’s Checked Exceptions in java.lang

ClassNotFoundException

CloneNotSupportedException

IllegalAccessException

InstantiationException

InterruptedException

NoSuchFieldException

NoSuchMethodException

Creating your own Exception Subclasses

Class MyException extends Exception {

private int detail;

MyException(int a) {

detail = a;

}

public String toString() {

return "MyException[ " + detail " ]";

}

}

class ExceptionDemo {

static void compute( int a) throws MyException {

if (a > 10)

throw new MyException(a);

System.out.println("Normal Exit");

}

public static void main (String args[]) {

try {

compute(1);

compute(50);

}catch (MyException e) {

//…..

}

}

}

Is This Answer Correct ?    16 Yes 8 No

What are different types of Exceptions?...

Answer / gagan jain

common exceptions:
Java has several predefines exceptions. the most common
exceptions that you may encounter are described below.

Arithmetic Exception:-
This exception is thrown when an exceptional arithmetic
condition has occurred. for example, a division by zero
generates such an exception.

Nullpointer Exception:-
This exception is thrown when an application attempts to
use null where an object is required. An object that has
not been allocated memory holds a null value. the
situations in which an exception is thrown include:
1. Using an object without allocating memory for it.
2. Calling the methods of a null object.
3. Accessing or modifying the attributes of null obect.

ArrayIndexoutof Bounds Exception
The exception Arrayindexoutofbounds Exceptions is thrown
when an attempt is made to access an array element beyond
the index of the array. for example, if you try to access
the eleventh element of an array that's has only ten
elements, the exception will be thrown.

Is This Answer Correct ?    16 Yes 9 No

What are different types of Exceptions?...

Answer / manikandan

Exception come is several flavours such as
RuntimeExceptions, Errors, Checked and Unchecked. The 3
major types of exception are ,

(1) RuntimeException : Error that can occur in almost any
code (Eg)NullPointerException

(2) Error : Serious error you really should not try to
catch, e.g. OutOfMemoryError.

(3) Checked Exception : Likely exceptional condition that
can only occur in specific places in the code e.g.
EOFException.

Is This Answer Correct ?    14 Yes 8 No

What are different types of Exceptions?...

Answer / haribabu kommi

Exceptions are three types

1.Runtime exceptions(un checked exceptions)
2.checked exceptions.
3.Error

Is This Answer Correct ?    10 Yes 6 No

What are different types of Exceptions?...

Answer / solehah

Some of the common exceptions you may encounter are:

1. ArrayIndexOutOfBoundsException - Thrown when attempting to access an array with an invalid index value (either negative or beyond the length of the array).
2. ClassCastException - Thrown when attempting to cast a reference variable to a type that fails the IS-A test.
3. IllegalArgumentException - Thrown when a method receives an argument formatted differently than the method expects.
4. IllegalStateException - Thrown when the state of the environment doesn't match the operation being attempted, e.g., using a Scanner that's been closed.
5. NullPointerException - Thrown when attempting to access an object with a reference variable whose current value is null.
6. NumberFormatException - Thrown when a method that converts a String to a number receives a String that it cannot convert.
7. AssertionError - Thrown when a statement's boolean test returns false.
8. ExceptionInInitializerError - Thrown when attempting to initialize a static variable or an initialization block.
9. StackOverflowError - Typically thrown when a method recurses too deeply. (Each invocation is added to the stack.)
10. NoClassDefFoundError - Thrown when the JVM can't find a class it needs, because of a command-line error, a classpath issue, or a missing .class file

Is This Answer Correct ?    3 Yes 1 No

What are different types of Exceptions?...

Answer / ravikiran(aptech mumbai)

checked and unchecked exceptions

Is This Answer Correct ?    25 Yes 24 No

What are different types of Exceptions?...

Answer / m.k.sreenivas

Checked exceptions:
A checked exception is some subclass of Exception (or
Exception itself), excluding class RuntimeException and its
subclasses. Each method must either handle all checked
exceptions by supplying a catch clause or list each
unhandled checked exception as a thrown exception.

Unchecked exceptions:
All Exceptions that extend the RuntimeException class are
unchecked exceptions. Class Error and its subclasses also
are unchecked.

Is This Answer Correct ?    2 Yes 1 No

Post New Answer

More Core Java Interview Questions

difference throws and throw in java

3 Answers  


What is a numeric literal?

0 Answers  


why constructor dont have returns type?

9 Answers   IBM,


explain System.out.println

107 Answers   Calpine Technologies, Care, Cognizant, CTS, IBM, IBS, LibSys, Oracle, Spiro Solutions, TCS,


What are other modifiers?

2 Answers   Wipro,






What is multithreading and its advantages?

0 Answers  


Is null an object in java?

0 Answers  


do I need to use synchronized on setvalue(int)? : Java thread

0 Answers  


when asub class inherits a super class and overrides a public method of super class in sub class(public method in super class). why these methods needs to be public in sub class. (otherwise compile time error).

3 Answers  


What means public static?

0 Answers  


Explain the hierarchy of java exception classes?

0 Answers  


How many types of java are there?

0 Answers  


Categories