Unit 4-Exception
Unit 4-Exception
Exception:
Exception is an abnormal condition or Exception is run time error.
1)Checked Exception
2)Unchecked Exception
Checked exceptions − A checked exception is an exception that
occurs at the compile time, these are also called as compile time
exceptions. These exceptions cannot simply be ignored at the
time of compilation, the programmer should take care of
(handle) these exceptions.
1.ArithmeticException
2.ArrayindexOutOfBoundsException
3.FileNotFoundException
4)NullPointerException
5.NumberFormatException
6.NegativeArraySizeException
class demo
{
public static void main(String args[])
{
int a,b,c;
try
{
a=18
b = 0;
c = a / b;
System.out.println("This will not be printed.");
}
catch (ArithmeticException e)
{
// catch divide-by-zero error
System.out.println("Division by zero.");
}
finally
{
System.out.println(“This final statement.");
}
}
Nested Try Catch:
If one try catch is inside other try catch block then it is called as
Nested try catch
class NestTry
{
public static void main(String args[])
{
try
{
int a = args.length;
int b = 42 / a;
System.out.println("a = " + a);
try
{
if(a==1) a = a/(a-a); // division by zero
if(a==2)
{
int c[] = { 1 };
c[42] = 99; // generate an out-of-bounds exception
}
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index out-of-bounds: " + e);
}
}
catch(ArithmeticException e)
{ System.out.println(e); }
} }
Multiple catch
In some cases, more than one exception could be raised by a single piece of code.
To handle this type of situation, you can specify two or more catch clauses, each
catching a different type of exception.
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.");
}}
throw keyword
The Java throw keyword is used to explicitly throw an
exception.
We can throw either checked or uncheked exception in java by
throw keyword.
throw exception;
Eg:
throw new IOException("sorry device error);
//Example for throw keyword...
Example
Class Declaration
Following is the declaration for java.lang.Throwable class −
5 StackTraceElement[] getStackTrace():
This method provides programmatic access to the stack trace information printed
by printStackTrace().