Tuesday, June 14, 2011

Runtime Exceptions Examples - Java

1.) Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6

int array[] = {4,5,22,33};
int a = array[6];


2.) Exception in thread "main" java.lang.NullPointerException

int array2[]  = null;
int b = array2[1];


3.) Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1

String string  = "Hello World";
String subString = string.substring(-1, 5);


4.) Exception in thread "main" java.lang.ArithmeticException: / by zero

int a = 4;
int b = a/0;


5.) Exception in thread "main" java.util.EmptyStackException

Stack<integer> ese = new Stack<integer>();
ese.pop();


6.) NumberFormatException

int no=0;
InputStreamReader inputStreamReader = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(inputStreamReader);
no =  Integer.parseInt(in.readLine() );


7.) java.lang.StackOverflowError

Call this method with a large long value

eg:- sof(7000);

static long sof(long n){
if(n==4) return 1;
else return n + (sof(n-1)) ;
}

No comments:

Post a Comment