throws , throw
“throws” Keyword :We can ‘throws’ keyword for delegating the responsibility of the Exception handling to the caller.
Ex:
class Sample
{
public static void main(String a[])throws InteruptedException
{
doStuff();
}
public static void doStuff()throws IE
{
doMoreStuff();
}
public static void doMoreStuff()
{
System.out.println(“hai”);
Thread.sleep(1000);
}
}
without ‘throws’ CTE: Unreported Exception java.lang.interuptedException ; must be caught or declared to be thrown. To avoid CTE(compile time error) another way in using try ---> catch block.
Ex:
class Sample
{
public static void main(String a[])
{
try
{
System.out.println(“hello”);
}
catch(IOException e){} --->CTE (fullychecked exception)
}
}
CTE: exception java.io.IOException is never thrown in the body of the corresponding try statement.
- If we are keeping the catch block for fully checked exception there should may be a chance of raising exception in the corresponding try block otherwise CTE saying XXXException is never thrown in the body of corresponding try statement.
try
{
System.out.println(“hai”);
}
catch(ArithematicException e) //valid no CTE(compile time error)
{ //unchecked exception }
Case 2: try
{
System.out.println(“hai”);
}
catch(Exception e) //valid no CTE
{
//Partially checked exception
}
Case 3:
try
{
System.out.println(“hello”);
}
catch(IOException e) //invalid CTE
{
// fully checked exception
}
Throw keyword:By using ‘throw ‘ keyword, over created customized exception objects are handed over to JVM.
Example:
class Sample
{
public static void main (String a[])
{
throw new ArithmeticException();
System.out.println(“hai”);
}// CTE: Unreachable statement
}
After throw we are not allowed to keep any statement, violation leads to CTE saying “unreachable statement”.
Customized Exceptions :
Based on the programming required sometimes we have to design our own Customized Exceptions.
Ex: Insufficient funds Exception
too young Exception
too old Exception
throw Example:
class TooYoungException extends RunTimeException
{
TooYoungException(String s)
{
super(s);
}
class Sample
{
public static void main(String a[])
{
int i=Integer.parseInt(arg[0]);
if(i>85)
throw new TooYoungException(“please wait some more time, you eill get married”);
else if(i<10)
throw new TooYoungException(“ur age is already crossed”);
else
throw new TooYoungException(“very soon you will get match”);
}
}
0 comments:
Post a Comment