Showing posts with label Exception Handling. Show all posts
Showing posts with label Exception Handling. Show all posts

write a program to show user defined Exception in the following condition: you have to enter the salary of a person at runtime and the salary must be a non-negative number & should be in between 6,000 & 20,000. and if it is not it will throw a user defined exception named.

class MyException extends Exception
{
 private int salary;

 MyException(int s)
  {
  salary=s;

  }
 public String toString()
  {
    return "MyException[" + salary +"]";
  }
 }
class ExceptionDemo
 {
  static void compute(int s) throws MyException
  {
   System.out.println("main exception(" + s + ")");
   if((s>60000)&&(s<20000))
   throw new MyException(s);
   System.out.println("no exception");
  }
 public static void main(String args[])
  {
  try
   {
   int s=Integer.parseInt(System.console().readLine("Enter the salary :"));
   compute(s);
   }
   catch(MyException e)
   {
      System.out.println("caugth;"+e);
   }
  }
 }

Write a program to Nested try blocks

class NestTry
 {
  public static void main(String args[])
  {
    try
    {
     int a = args.length;
     int b = 42 / a;
     System.out.println("a = " + a);
     try
      { // nested try block
       if(a==1) a = a/(a-a); // division by zero
      if(a==2)
       {
        int c[] = { 1 };
        c[42] = 99;
     }
   }
 catch(ArrayIndexOutOfBoundsException e)
  {
   System.out.println("Array index out-of-bounds: " + e);
  }
}
  catch(ArithmeticException e)
   {
    System.out.println("Divide by 0: " + e);
   }
  }
}

Write a program to try-catch-finally combination.

public class TryCatchFinally

{

   public static void main(String args[])
   {
      int a[] = new int[2];
      try
      {
         System.out.println("Access element three :" + a[3]);
      }
      catch(ArrayIndexOutOfBoundsException e)
      {
         System.out.println("Exception thrown  :" + e);
      }
      finally
      {
         a[0] = 6;
         System.out.println("First element value: " +a[0]);
         System.out.println("The finally statement is executed");
      }
   }
}

Write a program to Multiple catch blocks.

class Multicatch
{
public static void main(String args[])
{

try
{
int a=args.length;
System.out.println(" "+a);
int b=32/a;

int c[]=new int[5];
c[]=
}
catch(ArithmeticException e)
{
System.out.println("Ist catch"+e);
}
catch(ArrayIndexOutofBoundException e)
{
System.out.println("IInd catch"+e);
}
System.out.println("after catch");
}
}