How to handle runtime exceptions in java

RuntimeException is the superclass of all classes that throw exceptions during the normal operation of the Java VM (virtual machine). RuntimeException and its subclasses are unchecked exceptions. The most common exceptions are NullPointerException, ArrayIndexOutOfBoundsException, ClassCastException, InvalidArgumentException, etc.

  • NullPointerException is an exception thrown by the JVM when the program tries to call a method of a null object or perform other operations on a null object. Users should not try to handle this kind of anomaly, because it will only fix the problem rather than fix it completely.
  • ArrayIndexOutOfBoundsException is an exception that is automatically thrown by the JRE (Java Runtime Environment) when the program mistakenly tries to access a certain position in the collection that does not exist. This usually happens when the requested array index is negative or greater than or equal to the array size. Java arrays use zero-based indexes; therefore, the index of the first element of the array is zero, the index size of the last element is 1, and the index of the nth element is n-1.
  • The InvalidArgumentException is an exception raised when an invalid parameter is passed to a certain method on the server’s referenced connection.

Example 1:

// Create public class
public class GFG {

	public void GreeksForGreeks()
	{
		// throw exception
		throw new Greeks();
	}

	public static void main(String[] args)
	{
		try {
			new GFG().GreeksForGreeks();
		}
		// catch exception
		catch (Exception x) {
			System.out.println(
				"example of runtime exception");
		}
	}
}

// create subclass and extend RuntimeException class
class Greeks extends RuntimeException {

	// create constructor of this class
	public Greeks()
	{
		super();
	}
}

Output

example of runtime exception
 
Example 2:
class GFG {
	public static void main(String[] args)
	{
		// create array of 5 size
		int[] a = new int[] { 1, 2, 3, 4, 5 };

		// execute for loop
		for (int i = 0; i < 6; i++) {
			// print the value of array
			System.out.println(a[i]);
		}
	}
}

Output

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
at GFG.main(File.java:10)

 

Submit Your Programming Assignment Details