0% found this document useful (0 votes)
4 views

java exceptions

The document presents a Java program demonstrating custom exception handling with a class 'myExcept' for division by zero. The 'Divvy' class performs division and throws 'myExcept' when the denominator is zero, while the 'DivvyTest' class tests the functionality. The output shows the result of a valid division and handles the exception for division by zero appropriately.

Uploaded by

marybellesuez
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

java exceptions

The document presents a Java program demonstrating custom exception handling with a class 'myExcept' for division by zero. The 'Divvy' class performs division and throws 'myExcept' when the denominator is zero, while the 'DivvyTest' class tests the functionality. The output shows the result of a valid division and handles the exception for division by zero appropriately.

Uploaded by

marybellesuez
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

Exception example

public class myExcept extends Exception {

myExcept(int Num) {
super("Dividing by zero");
System.out.println("You were dividing " + Num + " by zero.");
}
}

public class Divvy {


public int myNum;
public int myDenom;
public int myResult;

public Divvy(int num, int denom) throws myExcept {


myNum = num;
myDenom = denom;
if (denom == 0) throw new myExcept(myNum);
myResult = myNum / myDenom;
}

public int result() {return myResult;}


}

public class DivvyTest {

public static void main (String[] args) {


Divvy d = null;
try {
d = new Divvy(4,2);
}
catch(myExcept e)
{
System.out.println("I can't divide 4 by 2.");
}

System.out.println("The result of 4/2 is " + d.result());

try {
Divvy e = new Divvy(4,0);
}
catch(myExcept e)
{
System.out.println("I can't divide 4 by 0.");
}
finally {
System.out.println("Finishing up");
}
}}

THE OUTPUT:

The result of 4/2 is 2


You were dividing 4 by 0.
I can't divide 4 by 0.
Finishing up

You might also like