Page 2 of 2 FirstFirst 12
Results 11 to 12 of 12

Thread: Write your own exception in java !!!

  1. #11
    Join Date
    Aug 2010
    Location
    Lancs, United Kingdom
    Beans
    1,588
    Distro
    Ubuntu Mate 16.04 Xenial Xerus

    Re: Write your own exception in java !!!

    Quote Originally Posted by vikkyhacks View Post
    In C++ we have operator overloading to change the operator's behavior at runtime, any such modifications or ideas such that the "/" throws myException (the exception that I wrote) in these case ??? If it can throw an arithmetic exception then there should be a way to throw user defined exceptions ....
    Java does not have operator overloading. You cannot change the behaviour of /

    Options:
    1.
    Code:
    if (n2 == 0) {
        throw new MyException();
    }
    System.out.println(MyArithmetic.integerDivide(n1, n2));
    2.
    Code:
    try {
        System.out.println(n1 / n2);
    }
    catch (java.lang.ArithmeticException arithmeticException) {
        throw new MyException();
    }
    3. Replace the operator with some class & function which avoids or translates the arithmeticException as above.
    Code:
    System.out.println(MyArithmetic.integerDivide(n1, n2));

  2. #12
    Join Date
    Jun 2007
    Location
    Maryland, US
    Beans
    6,288
    Distro
    Kubuntu

    Re: Write your own exception in java !!!

    Quote Originally Posted by kevinharper View Post
    PS: Trust me, dwhitney67 knows what he's talking about in all-things-programming.
    Thanks for the commendation, however I can assure you that I don't know everything related to programming. I experiment a lot, try to read, and I try to remember what works and what doesn't.

    As spjackson has pointed out to the OP, operator-overloading is a feature that is not available with Java. Oftentimes if one wants specialized behavior from their application that is not provided by the constructs of the language itself, then one must develop a wrapper function/class to provide the functionality they desire.

Page 2 of 2 FirstFirst 12

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •