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

Practice Programs Exceptions

Solution

Uploaded by

myraggy.127
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)
5 views

Practice Programs Exceptions

Solution

Uploaded by

myraggy.127
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/ 2

Practice Programs

1. A method that returns a special error code can sometimes cause problems. The
caller might ignore the error code or treat the error code as a valid return value. In
this case it is better to throw an exception instead. The following class maintains
an account balance and returns a special error code.

public class Account


{
private double balance;
public Account()
{
balance = 0;
}
public Account(double initialDeposit)
{
balance = initialDeposit;
}
public double getBalance()
{
return balance;
}
// returns new balance or -1 if error
public double deposit(double amount)
{
if (amount > 0)
balance += amount;
else
return -1; // Code indicating error
return balance;
}
// returns new balance or -1 if invalid amount
public double withdraw(double amount)
{
if ((amount > balance) || (amount < 0))
return -1;
else
balance -= amount;
return balance;
}
}
Rewrite the class so that it throws appropriate exceptions instead of returning -1 as
an error code. Write test code that attempts to withdraw and deposit invalid
amounts and catches the exceptions that are thrown.

2. Write a Java program to create a method that takes a string as input and throws
an exception if the string does not contain vowels.

3. Write a program that allows the user to compute the remainder after the division
of two integer values. The remainder of x / y is x % y. Catch any exception thrown
and allow the user to enter new values.

You might also like