简体   繁体   中英

Exceptions. How do I fix that? First steps

few weeks ago I have starded learning java. Im new and I make many mistakes. Today Im trying to learn about exceptions. I wrote a program which compute square of rectangle, but it doesnt works when i put in side "a" for example c letter. I would like if it shows to me string like "We have a problem ;)", but it throws error. Can you help me?

package Learning;
import java.io.*;
import java.util.Scanner;

public class Exceptions {
    public static void main(String[] args) throws IOException {
        double a,b,wynik;
        Scanner odc = new Scanner(System.in);
        try {
            System.out.println("Enter side a: ");
            a = odc.nextDouble();
            System.out.println("Enter side b: ");
            b = odc.nextDouble();
            wynik=a*b;
            System.out.println("Field equals: "+wynik);
        }
        catch(NumberFormatException e){
            System.out.println("We have a problem ;)");
        }
    }
}

When i put in side a, "c" letter i have something like that:

Exception in thread "main" java.util.InputMismatchException
    at java.base/java.util.Scanner.throwFor(Scanner.java:939)
    at java.base/java.util.Scanner.next(Scanner.java:1594)
    at java.base/java.util.Scanner.nextDouble(Scanner.java:2564)
    at Learning.Exceptions.main(Exceptions.java:11)

I need to see: "We have a problem ;)"

catch the InputMismatchException :

catch(NumberFormatException | InputMismatchException e){ ... }

System.out.println("We have a problem ;)"); will be executed if either a NumberFormatException or InputMismatchException arises.

if you want to output different result based on the exception type then create another catch block for InputMismatchException .

Your code never throw any NumberFormatException .
The impossibility to convert the input to a double is already conveyed by InputMismatchException .

Note that NumberFormatException and InputMismatchException are unchecked exceptions (they derive from RuntimeException).
This kind of exception may be thrown even if these are not declared as thrown by any invoked methods.
So generally you may want to catch them because you know that they may be thrown and you want to handle it. But you should be aware to catch only them when these may be effectively thrown as it makes code clearer.
Here it is not the case.

So in your case that is enough :

try {
    System.out.println("Enter side a: ");
    a = odc.nextDouble();
    System.out.println("Enter side b: ");
    b = odc.nextDouble();
    wynik=a*b;
    System.out.println("Field equals: "+wynik);
}
catch(InputMismatchException e){
    System.out.println("We have a problem ;)");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM