L31 finally, throws keyword
L31 finally, throws keyword
Keywords
throw
throw ThrowableInstance;
throws
• A throws clause lists the types of exceptions that a method might throw.
6
import java.io.IOException;
TestIface
{
void m() throws IOException
{
throw new IOException("device error");//checked exception
}
public static void main(String args[])
{
Here is the output generated by running this
try example program:
{
TestIface obj=new TestIface(); Caught exception: device error
obj.m();
System.out.println("normal flow...");
}
7
If an exception is thrown, the finally block will execute even if no catch statement
matches the exception.
catch (Exception e)
{ System.out.println("Exception caught");
}
} }
11
class FinallyDemo
{
static void procB()
{ try
inside procB
{ System.out.println("inside procB");
procB’s finally
return;
}
finally { System.out.println("procB's finally"); }
}
public static void main(String args[])
{
procB();
}
}
12
class FinallyDemo
{ static void procC()
{ try
{ System.out.println("inside procC");
}
finally
{ System.out.println("procC's finally");
} inside procC
procC’s finally
}
public static void main(String args[])
{
procC();
}
}
13
Creating our own exception
Subclasses
class MyException extends Exception
{ int detail;
MyException(int a)
{ detail = a;
}
14
class ExceptionDemo
{ static void compute(int a) throws MyException
{ System.out.println("Called compute(" + a +
")");
if(a > 10)
throw new MyException(a);
System.out.println("Normal exit");
} Called compute(1)
public static void main(String args[]) Normal exit
{ try Called compute(20)
{ compute(1); Caught MyException[20]
compute(20);
}
catch (MyException e)
{ System.out.println("Caught " + e);
}
}
} 15
Throwable
Exception Error