Monday, 11 November 2013

Lab 14 - Exception


You  will practice how to report and handle an error condition.
1. Create a custom class named DivideException that extend exception.
2. Create a class MyMath and type in the following code:

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

{
int quotient = divide(10, 5);
System.out.println(quotient);
quotient = divide(10, 0);
System.out.println(quotient);
quotient = divide(10, 1);
System.out.println(quotient);
}
public static int divide(int dividend, int divisor)
{

    return (int) dividend/divisor;
}
}



3.  Make changes to the divide  method to throw the custom DivideException with message of "Cannot divide lor"
4. Catch the specific error accordingly and print the error message.

1 comment:

  1. public class MyMath
    {
    public static void main(String[] args)
    { try {
    int quotient = divide(10, 5);
    System.out.println(quotient);
    quotient = divide(10, 0);
    System.out.println(quotient);
    quotient = divide(10, 1);
    System.out.println(quotient);

    }catch ( DivideException E){
    System.out.println(E.getMessage());

    } catch ( Exception E){
    System.out.println(E.getMessage());
    }
    }


    public static int divide(int dividend, int divisor) throws Exception
    { int result ;
    if (divisor != 0 )
    result = dividend/divisor;
    else {
    throw new DivideException("Cannot divide by 0 lor") ;

    }

    return result;
    }


    }

    class DivideException extends Exception {

    public DivideException(String msg){
    super(msg);
    }
    }

    ReplyDelete