Java Tutorials

A Custom Class Exception Handeling

“A Custom Class Exception Handeling” Is an example, that will help you to understand the concept of custom class exception.

There are two classes

1. The controller ExceptionQ5

2- The Custom InvalidPositionException

The ExceptionQ5 Class:


import java.util.*;

public class ExceptionsQ5 {
/**

* @param args

*/

public static void main(String[] args) throws Exception {

// TODO Auto-generated method stub

try {

int [] someArray = {12,9,3,11};

int position = getPosition();

display(someArray, position);

}

catch (InvalidPositionException e) {

System.out.println(e.getMessage());

}

catch (Exception e) {

System.out.println("The Exception is " + e.getMessage());

e.printStackTrace();

}

finally {

System.out.println("End of Program");

}

}

static int getPosition() throws InvalidPositionException {

System.out.println("Enter array position to display");

Scanner sc = new Scanner(System.in);

String positionEntered = sc.nextLine();

int position = Integer.parseInt(positionEntered);

if(position < 0) {

throw new InvalidPositionException();

} else {

return position;

}

}

static void display(int[] arrayIn, int positionIn) {

System.out.println("Item at this position is " + arrayIn[positionIn]);

}

}

The InvalidPositionException Class:


public class InvalidPositionException extends Exception {

public InvalidPositionException() {

super("There is no index for entered position");

}

public InvalidPositionException(String messageIn) {

super(messageIn);

}

}


Leave a Reply

Your email address will not be published. Required fields are marked *