try-catch doesn't catch IOException - java

In the following code, I get the Unreachable catch block for IOException. This exception is never thrown from the try statement body error(underlined) with the IOException in } catch (IOException e){ what am I doing wrong?
class driver {
public static void main(String[] args) {
// TODO Auto-generated method stub
Customer forrest = new Customer("Forrest Gump", 1,
"42 New Street, New York, New York");
Customer random = new Customer("Random Name", 2,
"44 New Street, New York, New York");
Customer customer[] = { null, forrest, random };
int whichOption = 1;
int id = 0;
char action = ' ';
char accSrc = ' ';
char accDest = ' ';
double amount = 0;
BankAccount src = null;
do {
try{
// process JOptionPane input information
String input = JOptionPane
.showInputDialog("Please enter your transaction information: ");
Scanner s = new Scanner(input);
id = Integer.parseInt(s.next());
action = Character.toUpperCase((s.next().charAt(0)));
if (action == 'T') {
amount = s.nextDouble();
accSrc = s.next().charAt(0);
accDest = s.next().charAt(0);
} else if (action == 'G' || action == 'I') {
accSrc = s.next().charAt(0);
} else {
// if D,W
amount = s.nextDouble();
accSrc = s.next().charAt(0);
}
} catch (IOException e){
}
// taking action accordingly (T)ransfer, (D)eposit, (W)ithdraw, (I)nterest
if (action == 'T') {
(customer[id].getAccount(accSrc)).transfer(amount,
customer[id].getAccount(accDest));
} else if (action == 'G') {
System.out.println("The current balance on your " + accSrc
+ " account is "
+ customer[id].getAccount(accSrc).getBalance() + "\n");
} else if (action == 'D') {
(customer[id].getAccount(accSrc)).deposit(amount);
} else if (action == 'W') {
(customer[id].getAccount(accSrc)).withdraw(amount);
} else if (action == 'I') {
(customer[id].getAccount(accSrc)).computeInterest();
}
whichOption = JOptionPane
.showConfirmDialog(null , "Do you want to continue?");
System.out.println("The balance on " + customer[id].getName()
+ " auto account is " + customer[id].A.balance);
System.out.println("The balance on " + customer[id].getName()
+ " savings account is " + customer[id].S.balance);
System.out.println("The balance on " + customer[id].getName()
+ " checkings account is " + customer[id].C.balance);
System.out.println("The balance on " + customer[id].getName()
+ " loan account is " + customer[id].L.balance + "\n");
} while (whichOption == 0);
}
}

It is because none of the operations you perform inside try/catch throws IOException.
As per Scanner javadoc
Most of the Scanner class methods throws either FileNotFoundException (Which is not applicable in your case because not reading from file) (or) IllegalArgumentException (or) IllegalStateException
You need to change IOException to either of above exceptions (or) remove try/catch.

You can remove the IOException and the try catch since none of the statements inside the try catch is throwing this exception

Seems like nothing you are doing in that try block is throwing the IOException

No method call in that try block throws a IOException, that is why the catch is an unreachable code.
You can safely remove both the try and the catch, as that situation will never happen.

Your catch block is empty, indicating that you weren't really going to handle the exception, anyway. You probably had some code in there that made you catch it, but now you don't have it anymore. Just remove the entire surrounding try-catch and there will be no further problems.

try/catch block is empty and code is not throw IOException but it may throw other exceptions.

Related

Make a loop AND catch using Strings instead of ints? (java)

I'm trying to make a text based rock paper scissors. I want the player to choose what they want to play to, for example "best (user response/2 + 1) out of (user response)" then it asks for verification if they would like to play to that number. If they say yes it continues the game with that score, if no it loops back up and lets them choose another number and I have an else that reminds them they can either select yes or no. When they are originally asked, letters don't effect and they are asked to try again. On the second loop around (when you say no) if you enter a String instead of an Int it crashes. Here what I have.
System.out.println("Best of:");
String line = userIn.nextLine();
while (true) {
if (line.length() > 0) {
try { //try catch to stop strings for a response
bestOf = Integer.parseInt(line);
break;
} catch (NumberFormatException e) {
}
}
System.out.println("Please enter a number");
line = userIn.nextLine();
}
System.out.println("Okay, so you want to play best " + (bestOf / 2 + 1) + " of " + bestOf + "?");
String response2 = userIn.nextLine();
while (true) {
if (response2.contains("n")) {
System.out.println("What do you wish to play to then, " + name + "?");
bestOf = userIn.nextInt();
response2 = "y";
} else if (response2.contains("y") || response2.contains("Y")) {
winScore = (bestOf / 2 + 1);
System.out.println("Okay, best " + (bestOf / 2 + 1) + " of " + bestOf + " it is!");
break;
} else {
System.out.println("That's not a valid response! Try again.");
response2 = userIn.nextLine();
}
}
Instead of using parseInt use the string, in other words the input take it as string (even if is a number) them use the function "isNumber" too check if the string the user put is a number if not, do a while
System.out.println("Best of:");
String line = userIn.nextLine();
String aux = line;
do{
if (line.length() > 0)
aux = line;
if(!isNumeric(aux)){
System.out.println("Please enter a number");
line = userIn.nextLine();
}
}while(!isNumeric(aux));
bestOf = Integer.parseInt(aux);
so
public static boolean isNumeric(String str) {
try {
double d = Double.parseDouble(str);
} catch (NumberFormatException nfe) {
return false;
}
return true;
}
You can extract your loop as a method and use it in second case as well.
private Integer readInt(Scanner scanner){
String line = scanner.nextLine();
while (true) {
if (line.length() > 0) {
try { //try catch to stop strings for a response
Integer result = Integer.parseInt(line);
return result;
} catch (NumberFormatException e) {
}
}
System.out.println("Please enter a number");
line = scanner.nextLine();
}
}
or even better:
private Integer readInt(Scanner scanner){
Integer result;
do{
try{
return scanner.nextInt();
} catch (InputMismatchException e){
scanner.nextLine();
System.out.println("Please enter a number");
}
} while (true);
}

Java validating Scanner Input with

How would I use InputMismatchException to determine if the value entered into the Scanner is not an integer? Basically, if they enter in a word instead of an integer I need to use InputMismatchException to return a message.
while (true) {
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
try{
Integer.parseInt(i);
} catch (InputMismatchException e) {
System.out.println("Sorry, " + i + " is not a number.");
}
if (i == 1) {
System.out.println("1 was selected");
} else {
System.out.println("1 was not selected");
}
Change your code as such:
while (true) {
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
try{
int i = Integer.parseInt(s);
if (i == 1) {
System.out.println("1 was selected");
} else {
System.out.println("1 was not selected");
}
} catch (NumberFormatException e) {
System.out.println("Sorry, " + s + " is not a number.");
}
}
Changes:
Note use of nextLine(). This is because it seems you want to use the input as part of your error message, and nextInt() won't let you do that.
We can now move the i declaration inside the try block, along with
the code that uses it, so we won't issue "1 was not selected" when the input was "ssss" or whatever.
We use NumberFormatException, as that's what Integer.parseInt()
throws when it can't parse an integer from the String.
This is what i mean
while (true) {
Scanner sc = new Scanner(System.in);
int i = -1;
try
{
i = sc.nextInt();
}
catch (InputMismatchException e)
{System.out.println("Sorry, " + i + " is not a number.");}
if (i == 1)
System.out.println("1 was selected");
else
System.out.println("1 was not selected");
}
I am new to the programming, I think I got the code for your question.
while (true) {
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
try{
int i = Integer.parseInt(s);
if (i == parseInt(i, 3)) {
System.out.println(s+" is selected");
} else {
System.out.println("Input value is " + s);
}
} catch (NumberFormatException e) {
System.out.println("Sorry, " + s + " is not a number.");
}}}
private static int parseInt(int i, int j) {
// TODO Auto-generated method stub
return 0;
}}
reference

Confused on what to do after catching exception

I am a little confused on what do after the catch statement in my code. After the exception is thrown and caught in the loop, the loop becomes infinite. I also found that entering a very long sequence (+10 or so) of numbers will cause the loop to go infinite. I am fairly new at exception handling in java, so a detailed description would be very educational.
public static void main(String[] args)
{
boolean cont = false;
while (!cont)
{
addInputNumber();
cont = tryAgain();
}
}
private static void addInputNumber ()
{
boolean valid;
int total;
int inputInt;
#SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
do
{
try
{
System.out.print("Enter a number(between 0 and 1000)");
inputInt = input.nextInt();
if(inputInt > 0 && inputInt < 1000)
{
valid = true;
total = (inputInt % 10) + ((inputInt / 10) % 10) + (inputInt / 100);
System.out.println("\n" + "The total of " + inputInt + " is " + total);
}
else
{
System.out.println("\n" + "ERROR---ENTER A NUMBER BETWEEN 0 AND 1000" + "\n");
valid = false;
}
}
catch(InputMismatchException ex)
{
System.out.println("\n" + "ERROR---ENTER A NUMBER BETWEEN 0 AND 1000" + "\n");
valid = false;
}
} while(!valid);
}
Change
catch(InputMismatchException ex)
{
System.out.println("\n" + "ERROR---ENTER A NUMBER BETWEEN 0 AND 1000" + "\n");
valid = true;
}
On the catch block, your variable valid was set to false.
Then on the code
while(!valid)
The condition will be true, and the loop go infinite
Your do while loop must end with
while(valid);
Because, once you catch the exception valid becomes false, and you may want to exit the loop if the exception is caught
What does the method tryAgain() do?
It looks like it calls addInputNumber(), right? If so, you don't need the loop in within the method addInputNumber().
I think you're problem is not of what to do in the catch block, but of program structure. You're using two loops, and you probably just need one. You could have addInputNumber() to return a boolean.

How come readLine() is not blocking?

Given the following code, the first call to readLine() is not blocking, both "Enter name:" and "Enter address:" are printed at the same time, and address gets assigned to whatever is entered. Why? I've tried putting them in separate try blocks, getting rid of the loop and generally reordering things.
public class AddressReader {
public static void main(String[] args) {
Path file = Paths.get("d:/java IO/addresses.txt");
try {
Files.createDirectories(file.getParent());
} catch (IOException e) {
System.err.println("Error craeting directory: " + file.getParent());
e.printStackTrace();
System.exit(1);
}
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int c = 0;
try {
System.out.println("<a>dd an entry or <r>ead entries");
c = br.read();
} catch (IOException e) {
System.out.println("An error has occured, try again");
}
switch (c) {
case 'a':
String name = null;
String address = null;
while (name == null || name == "" || address == null || address == "") {
try {
System.out.println("Enter name:");
name = br.readLine();
System.out.println("Enter address:");
address = br.readLine();
} catch (IOException e) {
System.out.println("An error has occured, try again");
}
System.out.println("name = " + name);
System.out.println("address = " + address);
}
//writeEntry(file, name, address);
break;
case 'r':
//readEntries(file);
break;
default:
System.out.println("Invalid entry, try again.");
}
}
}
This is because of this line:
c = br.read();
This does not consume the new-line character that is produced by pressing ENTER.
To solve this issue, use this instead:
c = br.readLine().charAt(0);
Over and above whats already been said, for what you're trying to do I suggest using the Console instead:
Console console = System.console();
String name = console.readLine("Create a name.");
char[] password = console.readPassword("Create a password.");
System.out.println(name + ":" + new String(password));

why does my break statement breaks out of the entire program?

The break; statement in my Exception clause stops the entire program if my have improper input to the JOptionPane, it would not execute what I have after the catch block, why is that?
public static void main(String[] args) {
// TODO Auto-generated method stub
Customer forrest = new Customer("Forrest Grump", 1,
"42 New Street, New York, New York");
Customer random = new Customer("Random Name", 2,
"44 New Street, New York, New York");
Customer customer[] = { null, forrest, random };
int whichOption = 1;
int id = 0;
char action = ' ';
char accSrc = ' ';
char accDest = ' ';
double amount = 0;
BankAccount src = null;
do {
try{
// process JOptionPane input information
String input = JOptionPane
.showInputDialog("Please enter your transaction information: ");
Scanner s = new Scanner(input);
id = Integer.parseInt(s.next());
action = Character.toUpperCase((s.next().charAt(0)));
if (action == 'T') {
amount = s.nextDouble();
accSrc = s.next().charAt(0);
accDest = s.next().charAt(0);
} else if (action == 'G' || action == 'I') {
accSrc = s.next().charAt(0);
} else {
// if D,W
amount = s.nextDouble();
accSrc = s.next().charAt(0);
}
} catch (Exception e){
System.out.println("Invalid input!");
break;
}
// taking action accordingly (T)ransfer, (D)eposit, (W)ithdraw, (I)nterest
if (action == 'T') {
(customer[id].getAccount(accSrc)).transfer(amount,
customer[id].getAccount(accDest));
} else if (action == 'G') {
System.out.println("The current balance on your " + accSrc
+ " account is "
+ customer[id].getAccount(accSrc).getBalance() + "\n");
} else if (action == 'D') {
(customer[id].getAccount(accSrc)).deposit(amount);
//You have successfully depositted $xx.xx
} else if (action == 'W') {
(customer[id].getAccount(accSrc)).withdraw(amount);
} else if (action == 'I') {
(customer[id].getAccount(accSrc)).computeInterest();
}
whichOption = JOptionPane
.showConfirmDialog(null , "Do you want to continue?");
System.out.println("The balance on " + customer[id].getName()
+ " auto account is " + customer[id].A.balance);
System.out.println("The balance on " + customer[id].getName()
+ " savings account is " + customer[id].S.balance);
System.out.println("The balance on " + customer[id].getName()
+ " checkings account is " + customer[id].C.balance);
System.out.println("The balance on " + customer[id].getName()
+ " loan account is " + customer[id].L.balance + "\n");
} while (whichOption == 0);
}
}
because using break you are jumping out of the loop (and that is the end of your program), if you wish to execute after catch block part, simply remove break;
See
document
I suspect you wish to continue, not break. See the difference here:
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html
continue tells the loops to skip all of the following statements in the loop body and return to the top of the loop body, recheck the condition, and then continue looping normally from there.
break tells the loop to end immediately, ignoring any further instructions in the loop body.
break escapes from the enclosing loop, which in your case means the end of main...
You're breaking out of the loop and there's nothing left after the loop in your main method. If you want to continue looping, replace the break; with continue;.

Categories