Java for Android Tutorial #11: Classcastexception handling





Code:


Method 1:
package com.example;
public class java {
    public static void main(String[] str) {

        Object string = "1";
        String string1 = (String)string;
        int integer = Integer.parseInt(string1);
        System.out.println(integer);
    }
}

Method 2:

package com.example;
public class java {
    
  public static void main(String[] str) {
        
    Object string = "1";
        try
        {
            int integer = (int)string;
        }
        catch(ClassCastException e){
            System.out.println("Please properly convert String into integer");
        }
 }
}

Class cast exception is an important type of exception. In this example, I have taken example of string and integers. But, it is more common with the concept of classes.

Comments

Popular Posts