Java For Android #14: Indepth look into exception handling


Code:
public class java {
 public static void main(String[] str) {
        String denom = "0";
        try {
            int denominator = Integer.parseInt(denom);
            int numerator = 231;
            int remainder = numerator % denominator;
            if (remainder == 0) {
                System.out.println(denominator + " is a factor of " + numerator);
            }
        }
        catch(ArithmeticException|NumberFormatException e) {
            if (e instanceof ArithmeticException) {
                System.out.println(e.getMessage());
                System.out.println("You can't divide any number by 0");
            }
            else if (e instanceof NumberFormatException) {
                System.out.println(denom + " is not an integer");
            }
        }
    }
}

Coders know the importance of handling the exceptions in an effective way. In this tutorial, I have continued from the last one and tried to dig deep into the exception handling especially catch statement. In the end, I have explained the 'finally statement' which is used with try..catch statement. It can come extremely handy in multiple cases.

Comments

Popular Posts