Tag Archives: UncheckedException

[Solved] java.lang.IllegalStateException: No match found : Regular Expression

java.lang.IllegalStateException is most common Runtime Exception and Unchecked Exception . It throws by JVM when trying to access object methods which are not allowed on certain cases.

In below example matcher.group(1) throwing IllegalStateException as “not match” . In below case as java.lang.Regex first we should call to matcher.find() method to get match in text for specific regular expression then based on matcher.group() we can get match text.

package com.test.exceptions;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegularExpressionTest {

	public static void main(String[] args) {
		String text = "Facing Issues on IT";
		Pattern pattern = Pattern.compile("\\w");
		Matcher matcher = pattern.matcher(text);
		if (matcher != null) {
			System.out.println(matcher.group(1));//Exception on this point
			System.out.println("Match Count :" + matcher.groupCount() +matcher.find());
		}
	}
}

Output

Exception in thread "main" java.lang.IllegalStateException: No match found
	at java.util.regex.Matcher.group(Unknown Source)
	at com.test.exceptions.RegularExpressionTest.main(RegularExpressionTest.java:13)

Solution 

In below code match.find() not called before matcher.group(1) that’s why throwing IllegalStateException.

Summary

  • Explain about IllegalStateException and Example
  • For Regular Expression in java.lanag.Regex what need to take care.
  • How to solve it.

 

Advertisements

[Solved] ClassCastException :A cannot be cast to B : Example

java.lang.ClassCastException is RuntimeException and Unchecked Exception which throws when code has attempted to cast an object to a subclass or class of which it is not an instance.

How to Fix ClassCastException ?

  • Always careful when try to cast an object of a class into another class. Make sure that new  type class belongs to one of its parent classes.
  • Use Generics to prevent ClassCastException because Generics provide compile time checks to develop type-safe applications so that issue identified on compile time.

Note: The conversion is valid only in cases where a class extends a parent class and the child class is casted to its parent class.

Example :
Below are two example of ClassCastException where type casting an objet to different type which is not sub class of object class.

Example 1: Here first converting Integer Object to Object class which is parent class of all classes and then after type casting object of Object class to String Object. Which not compatible with Integer class and not sub class of Integer that’s why throwing ClassCastException.

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class ClassCastExceptionExample {

	public static void main(String[] args) {
		/**
		 * when one tries to cast an Integer to a String, String is not an subclass of Integer, so a ClassCastException will be thrown.
	 */
		try
		{
		Object object= new Integer(10);
		System.out.println((String)object);
		}
		catch(ClassCastException ex)
		{
			ex.printStackTrace();
		}
	}

}

Example 2:
Here we  are trying to type cast an object of class A into an object of class B, and they aren’t compatible, we will get a class cast exception.

Let’s think of a collection of classes from below example

class A {}
class B extends A {…}
class C extends A {…}
We can cast any of these things to Object, because all Java classes inherit from Object.
We can cast either B or C to A, because they’re both “kinds of” A
We can cast a reference to an A object to B only if the real object is a B.
We can’t cast a B to a C even though they’re both A’s on that point will throw type cast exception.

public class A
{
}
public class B extends A
{
}
public class C extends A
{
}

package example;

public class ClassCastExceptionExample {

	public static void main(String[] args) {		

		try {
         A a=new A();
         A b=new B();
         A c=new C();

         B d=(B)b;
         B e=(B)c;// Exception on that point

		} catch (ClassCastException ex) {
			ex.printStackTrace();
		}
	}

}

Output:

java.lang.ClassCastException: example.C cannot be cast to example.B
	at example.ClassCastExceptionExample.main(ClassCastExceptionExample.java:27)

[Solved] ArrayIndexOutOfBoundException in JAVA

java.lang.ArrayindexOutOfboundsException is Runtime and Unchecked Exception. It’s subclass of java.lang IndexOutOfBoundsException.

ArrayIndexOutOfBoundsException is most common error in Java Program. It throws when an array has been accessed with an illegal index either negative or greater than or equal to the size of the array.

Points To Remember:

  •  Array index starts at zero and goes to length – 1, for example in an integer array int[] counts= new int[20], the first index would be zero and last index out be 19 (20 -1)
  • Array index cannot be negative, hence counts[-1] will throw java.lang.ArrayIndexOutOfBoundsException.
  • The maximum array index can be Integer.MAX_VALUE -1 because array accept data type of index is int and max allowed value for int is Integer.MAX_VALUE.

Constructors:

  • ArrayIndexOutOfBoundsException() : Constructs an  ArrayIndexOutOfBoundsException with no detail message.
  • ArrayIndexOutOfBoundsException(int index) : Constructs a new ArrayIndexOutOfBoundsException class with an argument indicating the illegal index.
  • ArrayIndexOutOfBoundsException(String s) : Constructs an ArrayIndexOutOfBoundsException class with the specified detail message.

Example :

public class ArrayOutOfBoundException {

	public static void main(String[] args) {
		String [] empArr={"Saurabh","Gaurav","Shailesh","Ankur","Ranjith","Ramesh"};
		//No of employee in array
		//Will through IndexOuhtOfBoundException because array having only six element of index 0 to 5
		try
		{
		String name=empArr[8];
		System.out.println("Employee :"+empArr[8]);
		}
		catch(ArrayIndexOutOfBoundsException ex)
		{
			ex.printStackTrace();
		}
	}
}

Output:

java.lang.ArrayIndexOutOfBoundsException: 8
	at example.ArrayIndexOutOfBoundsException.main(ArrayIndexOutOfBoundsException.java:11)<span id="mce_SELREST_start" style="overflow:hidden;line-height:0;"></span>

[Solved] java.lang.ArithmeticException: / by zero in JAVA

java.lang.ArithmeticException is Unchecked exception and sub class of java.lang.RuntimeException. It’s thrown when an exceptional condition occurred in Arithmetic Operations. It can also occurred by virtual machine as if suppression were disabled and /or the stack trace was not writable.

Constructors:

  • ArithmeticException() : Constructs an ArithmeticException with no detail message.
  • ArithmeticException(String s) : Constructs an ArithmeticException with the specified detail message.
Example :
An integer value “divide by zero” throw ArithmaticException.  In below example i am dividing int, double, float and long value with 0. For long and int type value it’s throwing Arithmatic Exception while for double and float printing special value as Infinity.  See below How to fix Arithmetic Exception? section.
package example;

public class ArithmaticExceptionExample {

	public static void main(String[] args) {
		int x=0;
		int y=5;
		double z=6;
		float l=6;
		long k=10L;
		//Integer value divide by integer value as 0 throw ArithmeticException
		try
		{
			System.out.println("Integer value divide by zero");
		System.out.println(y/x);
		}
		catch(ArithmeticException ex)
		{
			ex.printStackTrace();
		}
		//Double value divide by integer value as 0 No Exception special value Infinity
		System.out.println("Double value divide by zero");
		System.out.println(z/x);

		//Float value divide by integer value as 0 No Exception special value Infinity
		System.out.println("Float value divide by zero");
		System.out.println(l/x);

		//Long value divide by integer value as 0 throw ArithmeticException
		try
		{
		System.out.println("Long value divide by zero");
		System.out.println(k/x);
		}
		catch(ArithmeticException ex)
		{
			ex.printStackTrace();
		}

	}

}

Output:

Integer value divide by zero
java.lang.ArithmeticException: / by zero
	at example.ArithmaticExceptionExample.main(ArithmaticExceptionExample.java:15)
Double value divide by zero
Infinity
Float value divide by zero
Infinity
Long value divide by zero
java.lang.ArithmeticException: / by zero
	at example.ArithmaticExceptionExample.main(ArithmaticExceptionExample.java:31)

How to fix Arithmetic Exception?

In above example:

Y/X or K/X result ArithmeticException

What happens here is that since both the dividend and the divisor are int, the operation is an integer division, whose result is rounded to an int. Remember that an int can only contain whole number (of limited range, some 4 billion numbers approximately) That’ s why throwing Arithmatic Exception. same case for long value.

Z/X or L/X result special value Infinity

Here float (L) or double (X) precision value  divide by zero store in float and double value that why result is special value Infinity.