Method overloading on basis of exceptions in java

In this post we will learn how method can be overloaded on basis of  exceptions.

But now question which overloaded exception will be called.

Let’s take an example :

Ques. Let's say one method handles Exception and other handles ArithmeticException. Which method will be invoked when ArithmeticException is thrown?

Ans. Method which handles more specific exception will be called.

Program >
/** Copyright (c), AnkitMittal
* Main class */
public class ExceptionTest {
   void method(Exception e){
          System.out.println(e+" caught in Exception method");
   void method(ArithmeticException ae){
          System.out.println(ae+" caught in ArithmeticException method");
   public static void main(String[] args) {
          ExceptionTest obj=new ExceptionTest();
          obj.method(new ArithmeticException());
          obj.method(new IOException());
java.lang.ArithmeticException caught in ArithmeticException method caught in Exception method


No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...
//start paginationJs //end paginationJs