Thursday, 16 June 2016

Java Tutorial : Java unchecked exception(ArithmeticException)


Click here to watch in Youtube :
https://www.youtube.com/watch?v=NiXF1JSYwcM&list=UUhwKlOVR041tngjerWxVccw

Click the below Image to Enlarge
Java Tutorial : Java unchecked exception(ArithmeticException)
UnCheckedExceptionDemo1.java
/*
 * If you compile this code, it would compile
 * successfully however when you will run it, it would
 * throw ArithmeticException. That clearly shows that
 * unchecked exceptions are not checked at compile-time,
 * they are being checked at runtime.
 */

public class UnCheckedExceptionDemo1
{
    public static void main(String[] args)
    {
        int number1 = 10;
        int number2 = 0;
        /*
         * Since I'm dividing an integer with 0 it should
         * throw ArithmeticException
         */
        int result = number1 / number2;
        System.out.println(result);
    }

}
Output
Exception in thread "main" java.lang.ArithmeticException: / by zero
    at UnCheckedExceptionDemo1.main(UnCheckedExceptionDemo1.java:19)
UnCheckedExceptionDemo2.java
import java.util.Scanner;

public class UnCheckedExceptionDemo2
{
    public static void main(String[] args)
    {

        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter number1:\t");
        int number1 = scanner.nextInt();

        System.out.print("Enter number2:\t");
        int number2 = scanner.nextInt();

        scanner.close();

        try
        {
            int result = number1 / number2;
            System.out.println(result);
        }
        catch (ArithmeticException arithmeticException)
        {
            System.out
                    .println("Cannot divide an interger with zero."
                            + "So please enter number2 value greater then zero.");
        }

    }

}
Output
Enter number1:  15
Enter number2:  0
Cannot divide an interger with zero.So please enter number2 value greater then zero.
Click the below link to download the code:
https://sites.google.com/site/javaee4321/java/ExceptionDemo_UnCheckedException_App.zip?attredirects=0&d=1

Github Link:
https://github.com/ramram43210/Java/tree/master/BasicJava/ExceptionDemo_UnCheckedException_App

Bitbucket Link:
https://bitbucket.org/ramram43210/java/src/510730a975724a569c9343782aaa0bffd03472e7/BasicJava/ExceptionDemo_UnCheckedException_App/?at=master

See also:
  • All JavaEE Viedos Playlist
  • All JavaEE Viedos
  • All JAVA EE Links
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • JAVA Tutorial
  • No comments:

    Post a Comment