Showing posts with label exception handling. Show all posts
Showing posts with label exception handling. Show all posts

Saturday, February 18, 2012

Exception Handling Program in Java - How to Handle Exception in Java

This is sample example for how to handle exception in Java Programming. Here we handle error occurs due to array index out of bound.
Here handle error of array size exceed. In this example "exception_demo.java", array size is 10. Means we can insert element into array from arr[0] to arr[9] position. But trying to insert element at arr[10]. So ArrayIndexOutOfBoundsException occurs.

Program Code
//This program illustrates the Exception in a program.
public class exception_demo
{
 public static void main(String args[])
 {
  int []arr=new int[10];
  try
  {
   arr[10]=40; // Error occurs because arr range from 0 to 9
  }
  catch(ArrayIndexOutOfBoundsException e)
  {  
   System.out.println("Error Caught:  Array index out of bounds");
   arr[9]=40;
  }
  System.out.println("Beyond the exception point");
  System.out.println("Last element of array = "+arr[9]);
 }
}

Output

What is ArrayIndexOutOfBoundsException?

It is one of unchecked exception. Such exceptions are not listed in the list. This is identified at runtime. This occurs when array index is beyond the bounds means array size lime exceed.

Hope, this java code helps to understand exception handling in Java.

Friday, November 18, 2011

Exception Handling Program in PL/SQL Oracle

It is a sample PL/SQL Oracle exception handling program to handle errors. It is used for error tolerance and error avoidance.
In Pl/SQL exception is used to handle run time errors. When a run time error occurs then it moves to exception handler block in PL/SQL program.


Aim -PL/SQL program to perform exception handling.


Program: -
declare
  empn emp.empno%type;
  row_type1 emp%rowtype;
begin
  empn:=&empn;
  select * into row_type1 from emp where empno=empn;
  dbms_output.put_line('Name: '||row_type1.ename);
  exception when NO_DATA_FOUND then
  dbms_output.put_line('No such employee');
end;


Output: -

Enter value for empn: 7566
old 5: empn:=&empn;
new 5: empn:=7566;
Name: JONES

Enter value for empn: 1001 /* Such employee number(empno) is not in emp table */
old 5: empn:=&empn;
new 5: empn:=1001;
No such employee