Search This Blog

27 June, 2011

Exception handling: Java specific part-4


Part - 4
Exceptions: Throwable and checked exceptions
• Unlike C++, primitive types cannot be thrown.
Throwable types must be subclasses of
Throwable
• In the previous example we saw that an
uncaught exception leads to program
termination.
• Not all exceptions can be uncaught. Exceptions
may be divided into two classes
• Unchecked exceptions are
– subclasses of Error, or
– subclasses of RunTimeException
• checked exceptions: all others
Exceptions: catch all
• if a method can generate checked exceptions,
then these must be either
– specified using a throws clause
– or caught in a try block
else there is a compile-time error
• Unchecked exceptions need not be specified.
– hence lazy programmers tend to
subclass RunTimeException to produce
their exceptions.


Program:-

class MyException extends Exception
{
int exception_num;
}
public class CheckedException
{
int myMethod (int a, int b) throws
MyException
{
MyException e = new MyException();
if (a==0)
{
e.exception_num = 1;
throw e;
}
if (b==0)
{
e.exception_num=2;
throw e;
}
return a/b;}
public static void main (String args[])
{
CheckedException e = new
CheckedException();
try
{
e.myMethod (0, 1);
}

catch (MyException me)
{
System.out.println (me.exception_num);
}
}
}
• The above program will NOT compile if
– the throw clause is removed from
myMethod, or
– the catch clause is removed from main
(and no throws clause is provided to
main)


<<<-Part - 3     ------------------------   Part - 5 >>>   


No comments:

Post a Comment

Meetme@