Wednesday, January 13, 2010

Java's Throw Clause

Exceptions are errors that may occur because of invalid input, logic mistakes or programmer's omission or commission.  But, in Java these can be handled through some methods or can be remedied with better programming solutions.

Using try . . . catch and finally blocks, exceptions can be thrown and caught. Check the sample program below that throws an exception message once a negative integer is tried for square root. 

[+/-] show/hide

/* Square Root of an integer */
class ThrowDemo1
{ public static void main (String args[])throws IOException{
BufferedReader br=new BufferedReader (new InputStreamReader ( ));
System.out.println("Enter an integer: ");
int num=Integer.parseInt(br.readLine());

if (num<0)
throw new ArithmeticException();
System.out.println("Square root of "+num+" : "+Math.sqrt(num));
catch (ArithmeticException ae)
System.out.println("Negative number is not allowed.");

No comments: