In Java, an exception can be thought of as an error when the program is being run. There are numerous types of exceptions that may occur.

In order for an exception to be used in a program, it must throw it.
Below is a short example showing a basic exception:
public class Example{
public static void main(String args[]){
int x = -5;
if(x < 0){
throw new IllegalArgumentException("The number is too small!");
}
System.out.println(x);
}
}

The above example will simply throw a new exception. In general, it is of the form:

throw new ExceptionName("Error Message");


where throw is the keyword to generate an exception; new is creating the Exception object; ExceptionName is the name of the exception (see below); and the string "Error Message" is a useful message that the user will see when the exception is thrown.

In Java, there are many types of exceptions that are defined within the Java libraries. Below is chart of the most commonly seen exceptions that Java will generate.

1.IllegalArgumentException

-An exception to handle a problem with method or command-line arguments. One way to think of this is if the user does not give a command-line argument or the argument in a method is not in a certain range, this is the appropriate exception to be thrown.

2.NumberFormatException

-An exception to handle a problem when formatting a number(s). This is commonly seen when using any of the parseXXX methods of a certain class. Say that your string is "1234ff" and you call parseInt; when you get to the 'f', the exception will be thrown since 'f' is not a number.

3.ArrayIndexOutOfBoundsException


-The name says it all. This exception will occur when an index in an array is out of bounds in either direction (less than 0 or greater than or equal to its size).

4.NullPointerException

-Ah yes, the most commonly seen and most annoying exception of them all! This means that you are pointing at nothing (or null) perhaps in a linked list or even when dealing with a JOptionPane. The solution: a bottle of Tylenol and good debugging skills.

5.Exception


-The most general type of exceptions of them all. This will not specifically check for anything but will mean some kind of error occurred.


6.ArithmeticException


-Arithmetic error condition (for example, divide by zero).

7.ArrayStoreException

-Object type mismatch between the array and the object to be stored in the array.


8.StringIndexOutOfBoundsException

-Index is negative or greater than the size of the string.

9.IllegalThreadStateException

-Object type mismatch between the array and the object to be stored in the array.

10.ClassNotFoundException

-Unable to load the requested class.

Sample programs
An example of a built-in exception.

Sample Program 1

import java.io.*;
import java.util.*;

public class Example{

public static void main(String args[]){
StringTokenizer st;

try{
BufferedReader br = new BufferedReader(
new FileReader("input1.txt"));

String line = br.readLine();
double avg = 0.0;
int num = 0, count = 0;

while(line != null){
st = new StringTokenizer(line);

for(int i = 0; i < st.countTokens(); i++){
avg += Double.parseDouble(st.nextToken());
count++;
}
line = br.readLine();
}

br.close();

avg = avg/count;
System.out.println("Avg: " + avg);

}catch(Exception e){}
} //main
} //class



Sample Program 2

import java.io.* ;
import java.lang.Exception ;

public class DivideBy0 {

public static void main( String[] args ) {

int a = 2 ;
int b = 3 ;
int c = 5 ;
int d = 0 ;
int e = 1 ;
int f = 3 ;

try
{
System.out.println( a+"/"+b+" = "+div( a, b ) ) ;
System.out.println( c+"/"+d+" = "+div( c, d ) ) ;
System.out.println( e+"/"+f+" = "+div( e, f ) ) ;
}
catch( Exception except )
{
System.out.println( "Caught exception " +
except.getMessage() ) ;
}
}

static int div( int a, int b ) {

return (a/b) ;

}

}
The output of this application is shown here:
2/3 = 0
Caught exception / by zero


Sample Program 3

IllegalArgumentException program

public class NewExceptionName extends OldExceptionName{
public NewExceptionName(String gripe){
super(gripe); //super class: OldExceptionName
}
}
public class GradStudentException extends IllegalArgumentException{
public GradStudentException(String gripe){
super(gripe);
}
}
BufferedReader varName = new BufferedReader(
new FileReader("filename.txt"));
try{
BufferedReader br;
br = new BufferedReader(new FileReader("input.txt"));

//rest of reading code here

}catch(Exception e){
System.out.println("Error!");
}
Output
i= 0
i= 1
i= 2
i= 3
i= 4
i= 5
i= 6
Yikes! i= 7
Yikes! i= 8
Sum: 23


Sample Program 4


public class TryExample2{
public static void main(String args[]){
String str = "2346512aa";
int sum = 0;

for(int i = 0; i <= str.length(); i++){
try{
sum += Integer.parseInt(str.charAt(i) + "");
}catch(IndexOutOfBoundsException ioe){
System.out.print("Regular! ");
}catch(NumberFormatException nfe){
System.out.print("Yikes! ");
}finally{
System.out.println("i= " + i);
}
}
System.out.println("Sum: " + sum);
} //main
} //class

output:
i= 0
i= 1
i= 2
i= 3
i= 4
i= 5
i= 6
Yikes! i= 7
Yikes! i= 8
Regular! i= 9
Sum: 23

Sample Program 5

import java.io.*;
public class OutputExample{

public static void main(String args[]){

if(ars.length == 0){
System.out.println("String argument needed.");
System.exit(1);
}

String word = args[0];

try{
BufferedWriter bw = new BufferedWriter(
new FileWriter("output.txt"));

String ans = "";

for(int i = 0; i < word.length(); i++){
ans += word.substring(i);
bw.write(ans);
bw.newLine();
ans = "";
}

bw.close();

}catch(Exception e){}
} //main
} //class

output:
hello there
ello there
llo there
lo there
o there
there
there
here
ere
re
e

0 comments:

Post a Comment