Exception Handling In Java

Exception Handling:
java exception handling is managed via five keywords: try, catch, throws and finally. If an exception occur in try block it is thrown.your code can catch this exceptions (using catch) and handle it in some rational manner.to manually throw an exception,use the keyword throw

Exception Handling
syntax:
try{
//block of code to monitor for errors
}
catch(Exceptiontype1 exOb )
{
//exception handler for Exceptiontype1
}
finally
{
//block of code to be executed after try block ends
}

1.Exception handling example

import java.util.*;
class trycatch
{
public static void main(String[] args)
{
try
{
int a,b;
a=5;
b=a/0; //this statement create exception
}
catch(ArithmeticExecption e)
{
System.out.println("Exception Occured: Divide by Zero");
}
}
}

2.Throws and throws demo of exception handling

import java.util.*;
class newException extends Exception
{

}
class throw
{
static void method() throws new Exception
{
throws new newException();
}
public static void main(String args[])
{
try
{
method();
}
catch(newException e)
{
System.out.println("new Exception caught:"+e);
}
} 
}
OUTPUT:
new Exception caught:new Exception
Translate »