Home Tutorial Java Core Exception Exception Handling with and without using try catch block

 
 

Share on Google+Share on Google+
Exception Handling with and without using try catch block
Posted on: March 15, 2010 at 12:00 AM
Advertisement
In this tutorial it demonstrate the way of using exception handling. One using throws and other using try catch block

Description:

Without using try catch block. If you do not want to explicitly make try catch block then to you program write throws Exception to your method where Exception handling is required 

Code: 

class exceptionHandle {

      public static void main(String args[]) throws Exception {

            int a = 5;

            int b = a / 0;

            System.out.println(b);

      }

}

Output: 

Exception in thread "main" java.lang.ArithmeticException: / by zero

at exceptionHandle.main(exceptionHandle.java:7) 

Now the other way to use Exception Handling is by using try catch block shown in following code sample:

 class exceptionHandle {

      public static void main(String[] args) {

            try {

                  int a = 5;

                  int b = a / 0;

                  System.out.println(b);

            }

catch (Exception e) {

            System.out.println(e);

            }

      }

}

Output: 

java.lang.ArithmeticException: / by zero

Advertisement

Related Tags for Exception Handling with and without using try catch block:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: March 15, 2010

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com