How to use ValueError in catch java - java

I want to try and catch in java,
when I wrote the catch part it asked me for a parameter,
the parameter I want to use is ValueError (as meaning in python)
Example:
try {
System.out.print("Write your weight: ");
weight = input.nextDouble();
}
catch (ValueError){
System.out.print("You must write your weight in numbers: ");
weight = input.nextDouble();
}

When you are working with java if you use some IDEs(like intllij) it will suggest you what exception(s) you should catch and in this situation or when you know what exceptions you should catch(suppose ExceptionType1 and ExceptionType2) your code will be something like :
try {
//some code with multiple exceptions
} catch (ExceptionType1 ex){
//some code to handle your exceptions
} catch (ExceptionType2 ex){
//some code to handle your exceptions
} ....
but in general if you dont know what exception(s) you have, or you dont want to handle all of them, you could catch general Exception something like this:
try {
//some code with multiple exceptions
} catch (Exception ex){
//some code to handle your exceptions
}
and of course you could write your own exceptions

The nextDouble method of Scanner (which I assume is the type of input) can throw a few exceptions. You can only catch a type of exception that is possible to come back. If you are interested specifically if someone typed a bad answer (like 'yes' instead of a number) then you can catch InputMismatchException. If you're just wanting to capture any error at all you can catch the more generic Exception. In either case your catch statement must name the exception type and a variable name like this:
catch (InputMismatchException ex) { ... }
or
catch (Exception ex) { ... }
This way you can do something with the exception by calling methods on the ex variable.
Also, you show the catch simply trying again. This might work if the user types a bad value once, but not if it happens a second time. A better way to try again would be this:
weight = -1; // so we can tell if a valid weight was given
while (weight < 0) {
try {
System.out.print("Write your weight: ");
weight = input.nextDouble();
}
catch (InputMismatchException ex){
System.out.print("You must write your weight in numbers.");
}
}
This allows the question to be asked until they enter a valid value.

Related

why is the Catch exception e printing instead of doing what is in Try

I am confused why it is going to catch and print the error occurred message when I run my code since it runs and just prints the message I can't tell what the error could be
Note: this is my very first time using try and catch my professor told us to use it but haven't really learned how it works fully yet so I'm not sure if the problem is with that or if it's just with my code
public static void main (String [] args) {
try {
File file = new File("in.txt");
Scanner scanFile = new Scanner(file);
...
} catch(Exception e) {
System.out.println("Error");
}
}
Do not catch an exception unless you know what to do. It is common that you don't - most exceptions aren't 'recoverable'.
So, what do you do instead?
Simplest plan: Just tack throws Exception on your main method. public static void main(String[] args) methods should by default be declared to throws Exception, you need a pretty good reason if you want to deviate from this.
Outside of the main method, think about your method. Is the fact that it throws an exception an implementation detail (a detail that someone just reading about what the method is for would be a bit surprised by, or which could change tomorrow if you decide to rewrite the code to do the same thing but in a different way)? In that case, do not add that exception to the throws clause of your method. But if it is, just add it. Example: Any method whose very name suggests that file I/O is involved (e.g. a method called readFile), should definitely be declared to throws IOException. It'd be weird for that method not to throws that.
Occasionally you can't do that, for example because you're overriding or implementing a method from an interface or superclass that doesn't let you do this. Or, it's an implementation detail (as per 2). The usual solution then is to just catch it and rethrow it, wrapped into something else. Simplest:
} catch (IOException e) {
throw new RuntimeException("uncaught", e);
}
Note that the above is just the best default, but it's still pretty ugly. RuntimeException says very little and is not really catchable (it's too broad), but if you don't really understand what the exception means and don't want to worry about it, the above is the correct fire-and-forget. If you're using an IDE, it probably defaults to e.printStackTrace() which is really bad, fix that template immediately (print half the details, toss the rest in the garbage, then just keep on going? That's.. nuts).
Of course, if you know exactly why that exception is thrown and you know what to do about it, then.. just do that. Example of this last thing:
public int askForInt(String prompt) {
while (true) {
System.out.println(prompt + ": ");
try {
return scanner.nextInt();
} catch (InputMismatchException e) {
System.out.println("-- Please enter an integral number");
}
}
}
The above code will catch the problem of the user not entering an integer and knows what to do: Re-start the loop and ask them again, until they do it right.
Just add throws Exception to your main method declaration, and toss the try/catch stuff out.
There are a couple of problems with your current code:
catch (Exception e) {
System.out.println("Error occured...");
}
Firstly, you are not printing any information about the exception that you caught. The following would be better:
catch (Exception e) {
System.out.println(e.getMessage()); // prints just the message
}
catch (Exception e) {
System.out.println(e); // prints the exception class and message
}
catch (Exception e) {
e.getStackTrace(System.out); // prints the exception stacktrace
}
Secondly, for a production quality you probably should be logging the exceptions rather than just writing diagnostics to standard output.
Finally, it is usually a bad idea to catch Exception. It is usually better to catch the exceptions that you are expecting, and allow all others to propagate.
You could also declare the main method as throws Exception and don't bother to catch it. By default, JVM will automatically produce a stacktrace for any uncaught exceptions in main. However, that is a lazy solution. And it has the disadvantage that the compiler won't tell you about checked exceptions that you haven't handled. (That is a bad thing, depending on your POV.)
now null printed out.
This is why the 2nd and 3rd alternatives are better. There are some exceptions that are created with null messages. (My guess is that it is a NullPointerException. You will need a stacktrace to work out what caused that.)
Catching Exception e is often overly broad. Java has many built-in exceptions, and a generic Exception will catch all of them. Alternatively, consider using multiple catch blocks to dictate how your program should handle the individual exceptions you expect to encounter.
catch (ArithmeticException e) {
// How your program should handle an ArithmeticException
} catch (NullPointerException e) {
// How your program should handle a NullPointerException
}

How to avoid "variable might not have been initialized" near try/catch with System.exit

I want to avoid this ugly pattern:
Long foo = null;
Double bar = null;
try {
foo = Long.parseLong(args[0]);
bar = Long.parseLong(args[0]);
} catch (NumberFormatException e) {
System.out.println(USAGE);
System.exit(1);
}
doSomethingWith(foo, bar);
I know I can move the initialisations and doSomethingWith into the try block, but imagine:
doSomethingWith is actually several lines of conditional logic, many method calls, statements etc.
I don't want to be nesting blocks unnecessarily deeply
I want to avoid accidentally catch unexpected NumberFormatExceptions thrown from doSomethingWith.
I find the = null and above quite ugly, as well as the use of classes instead of primitives. This ugliness makes me suspect there's a better way to write this code.
My first vision is of course
long foo;
double bar;
try {
foo = Long.parseLong(args[0]);
bar = Long.parseLong(args[0]);
} catch (NumberFormatException e) {
System.out.println(USAGE);
System.exit(1);
}
doSomethingWith(foo, bar);
but we all know Java throws a couple variable might not have been initialized errors when you try to build that.
What's a better design pattern for this kind of problem? "Better" meaning (for me) does all of this
avoids the weird = null
avoids unnecessary class wrappers around primitives
doesn't nest deeply into the try block
doesn't catch/hide exceptions it wasn't meant to
If this is not possible, or if my concept of "pretty" code is wrong, please convince me and show the best that can currently be used.
The oddity here is that the compiler doesn't know that System.exit(1); will never return. If it knew that, it would be happy.
So all you need to do is give it something that it knows won't let you get from the catch block to after the try/catch. For example:
try {
foo = Long.parseLong(args[0]);
bar = Long.parseLong(args[0]);
} catch (NumberFormatException e) {
System.out.println(USAGE);
System.exit(1);
throw new RuntimeError("Make sure the end of the catch block is unreachable");
}
If you need to do this often, you might want to write a helper method, and throw the result of it (which you'll never use). That way you still only have a single line of code for "I want to quit now".
try {
foo = Long.parseLong(args[0]);
bar = Long.parseLong(args[0]);
} catch (NumberFormatException e) {
System.out.println(USAGE);
throw HelperClass.systemExit(1);
}
...
public class HelperClass {
public static RuntimeException systemExit(int exitCode) {
System.exit(1);
throw new RuntimeException("We won't get here");
}
}
Another option I've used quite a bit is to define a sort of "User error" exception. You can then catch that at the top level (in main), print any message and possibly display the usage. That way:
You can unit test user errors (unit testing System.exit is at least more awkward)
You have centralized handling of "what do I want to do if the user made an error" rather than including System.out.println(USAGE) in multiple places
You don't run into this definite assignment issue
So your code would then be:
try {
foo = Long.parseLong(args[0]);
bar = Long.parseLong(args[0]);
} catch (NumberFormatException e) {
throw new UserInputException("foo and bar must both be valid integers");
}
I couldn't resist! This is another cleaner (but longer) solution.
// SomeModel(a: long, b: long)
public static Optional<SomeModel> validate(final String[] args) {
try {
// Probably some other null checks and things like that here also
return Optional.of(new SomeModel(Long.parseLong(args[0]), Long.parseLong(args[1])));
} catch (final NumberFormatException e) {
System.out.println(USAGE);
System.exit(1);
}
return Optional.empty(); // Or use some other "defaults" for that model
}
public static void doSomethingWith(final SomeModel input) { // ...signature changed!
// Do your stuff here
}
public static void main(final String[] args) {
validate(args).ifPresent(it -> doSomethingWith(it));
}
This flow is more clear but it's more verbose. The validations are separated and there is nothing else to do to please the compiler. Having to mode the return might be a drawback, but it pays off later on.

Exception hierarchy/try-multi-catch

try {
throw new FileNotFoundException();
} catch (IOException e) {
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
Can someone tell me why the second catch block is not considered as unreachable code by the compiler? But in the following case:
try {
throw new FileNotFoundException();
} catch (Exception e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
The second catch block is considered unreachable?
After all, FileNotFoundException comes under IOException, just as it comes under Exception.
Edit Please clarify:
The compiler will know an exception is thrown by a method based on the method's throws clause. But it may not necessarily know the specific type of exception (under that class of exception). So if a method throws exception 'A', compiler won't know if the actual exception is 'A' or a subtype of 'A' because this is only determined at runtime. The compiler however will know that an exception of type 'X' is never thrown, so giving a catch block for X is erroneous. Is this right?
The compiler cannot assume that the only possible exception thrown from your try block will be a FileNotFoundException. That's why it doesn't consider the 2nd catch block to be unreachable in your first code sample.
What if, for some unknown reason, a RuntimeException gets thrown while creating the FileNotFoundException instance (entirely possible)? What then?
In your first code sample, that unexpected runtime exception would get caught by the 2nd catch block, while the 1st block would take care of the FileNotFoundException if it gets thrown.
However, in your 2nd code sample, any and all exceptions would get caught by the 1st catch block, making the 2nd block unreachable.
EDIT:
To better understand why the catch(Exception e) block in your first code is not considered unreachable by the compiler, try the following code, and notice how the the 2nd catch is definitely reachable:
public class CustomIOException extends IOException {
public CustomIOException(boolean fail) {
if (fail) {
throw new RuntimeException("the compiler will never know about me");
}
}
}
public static void main(String[] args) {
try {
throw new CustomIOException(true);
} catch(IOException e) {
System.out.println("Caught some IO exception: " + e.getMessage());
} catch(Exception e) {
System.out.println("Caught other exception: " + e.getMessage());
}
}
Output:
Caught other exception: the compiler will never know about me
TL;DR
The compiler considers that FileNotFoundException() may not be the only Exception thrown.
Explaination
JLS§11.2.3 Exception Checking
A Java compiler is encouraged to issue a warning if a catch clause can
catch (§11.2) checked exception class E1 and the try block
corresponding to the catch clause can throw checked exception class
E2, a subclass of E1, and a preceding catch clause of the immediately
enclosing try statement can catch checked exception class E3 where E2
<: E3 <: E1.
That means that if the compiler considers that the only exception possibly thrown by your catch block is a FileNotFoundException(), it will warn you about your second catch block. Which is not the case here.
However, the following code
try{
throw new FileNotFoundException();
} catch (FileNotFoundException e){
e.printStackTrace();
} catch (IOException e){ // The compiler warns that all the Exceptions possibly
// catched by IOException are already catched even though
// an IOException is not necessarily a FNFException
e.printStackTrace();
} catch (Exception e){
e.printStackTrace();
}
This happens because the compiler evaluates the try block to determine which exceptions has the possibility to be thrown.
As the compiler does not warn us on Èxception e, it considers that other exceptions may be thrown (e.g RunTimeException). Since it is not the compiler's work to handle those RunTimeExceptions, it lets it slip.
Rest of the answer is intersting to read to understand the mechanism behind exception-catching.
Schema
As you may see, Exception is high in the hierarchy so it has to be declared last after IOException that is lower in the hierarchy.
Example
Imagine having an IOException thrown. As it is inherited from Exception, we can say IOException IS-A Exception and so, it will always be catched within the Exception block and the IOException block will be unreachable.
Real Life Example
Let's say, you're at a store and have to choose pants. The seller tells you that you have to try the pants from the largest ones to the smallest ones and if you find one that you can wear (even if it is not your size) you must take it.
You'll find yourself buying pants too large for your size and you'll not have the chance to find the pants that fits you.
You go to another store : there, you have the exact opposite happening. You can choose your pants from smallest to largest and if you find one you can wear, you must take it.
You'll find yourself buying pants at your exact size.
That's a little analogy, a bit odd but it speaks for itself.
Since Java 7 : multi-catch
Since Java 7, you have the option to include all the types of Exceptions possibly thrown by your try block inside one and only catch block.
WARNING : You also have to respect the hierarchy, but this time, from left to right.
In your case, it would be
try{
//doStuff
}catch(IOException | Exception e){
e.printStackTrace();
}
The following example, which is valid in Java SE 7 and later,
eliminates the duplicated code:
catch (IOException|SQLException ex) {
logger.log(ex);
throw ex;
}
The catch clause specifies the types of exceptions that the block can
handle, and each exception type is separated with a vertical bar (|).
First case:
catch (IOException e) { // A specific Exception
e.printStackTrace();
}
catch (Exception e) { // If there's any other exception, move here
e.printStackTrace();
}
As you can see, first IOException is catched. This means we are aiming at just one specific exception. Then in second catch, we aim for any other Exceptions other than IOException. Hence its logical.
In second:
catch (Exception e) { // Move here no matter whatever exception
e.printStackTrace();
}
catch (IOException e) { // The block above already handles *Every exception, hence this won't be reached.
e.printStackTrace();
}
We catched any exception (whether its IOException or some other Exception), right in the first block. Hence second block will not be reached because everything is already included in first block.
In other words, in first case, we aim at some specific exception, than at any other exceptions. While in second case, we first aim at all/any Exception, than at a specific exception. And since we already dealt will all exceptions, having a specific exception later won't make any logical sense.

Try/Catch statement not catching exceptions

I'm trying to use a try/catch statement inside an inner class of an actionlistener but it does not catch the exceptions even when I deliberately trigger them. Here is the code excerpt:
btnPerformCalculation.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
double runtime = Math.abs(Double.parseDouble(txtRunTime.getText()));
double downtime = Math.abs(Double.parseDouble(txtDownTime.getText()));
double blockedtime = Math.abs(Double.parseDouble(txtBlockedTime.getText()));
double lineefficiency = 100 * runtime / (runtime + downtime + blockedtime);
try {
txtEfficiencyAnswer.setText(String.format("%.2f", lineefficiency));
} catch (Exception e) {
JOptionPane.showMessageDialog(frame, "Error:" + e.getMessage());
txtRunTime.setText("0");
txtDownTime.setText("0");
txtBlockedTime.setText("0");
}
}
});
The only exceptions that you are catching are in txtEfficiencyAnswer.setText(String.format("%.2f", lineefficiency));. All other calculations (e.g. transforming possibly null text values into doubles are done before the try-block, and therefore not caught.
Assuming that txtEfficiencyAnswer is either a JTextComponent or a JLabel, the only obvious reason for an exception in that block would be a NullPointerException if txtEfficiencyAnswer is null. If it is not null, then you will never enter the catch-block.
First, how are you sure that JOptionPane.showMessageDialog isn't throwing an exception? I recommend putting output or logging as the first statement in your catch. Second, not all "exceptions" are subclasses of Exception. Try using catch (Throwable e) to see if the specific problem you are having gets solved.
I do not recommend leaving the catch(Throwable e) in your code since that will catch very low level jvm problems as well. But it will at least help you understand what's happening.
Probably setText throw RuntimeException.
Change catch statement to catch (RuntimeException e)
Print stacktrace.

Learning Try-Catch

I'm a Java beginner so please bear with me
static int load = 100;
static int greet;
public void loadDeduct(int cLoad, int c){
int balance;
balance = cLoad - 7;
System.out.println("Your balance: " + balance);
}
public void loadDeduct(int tLoad){
int balance;
balance = tLoad - 1;
System.out.println("Your balance is: " + balance);
}
public static void main (String [] args){
int choice;
Scanner scan = new Scanner(System.in);
System.out.println("I'm a cellphone, what do you want to do?");
System.out.println("Press 1 to send SMS / Press 2 to Call");
choice = scan.nextInt();
CellphoneLoad N95 = new CellphoneLoad();
if (choice == 1){
N95.loadDeduct(load);
}else if (choice == 2){
N95.loadDeduct(load, greet);
}else{
System.out.println("Invalid Option!!!");
}
How do I implement the exception handling with this program?
I'm not quite sure how to use the catch block as we weren't taught yet about the whole exceptions thing. It was just an exercise we were asked to do. I want to replace the if else statements with a try-catch blocks... is that possible?
One important principle to consider with exceptions in Java is that there are two types:
1. Runtime
2. Typed/explicit (for lack of a better word)
Runtime exceptions should be thrown when there is a programming error and generally they should not be caught unless you are catching at the top level to report an error.
Typed/Explicit exceptions are decorated on method calls and should be there so the caller can take some action on them.
In the case of the code above, there isn't really a place that feels like it should use exception handling.
And as Patrick pointed out, you don't generally want to use exceptions for flow control.
It is not ideal to use Exceptions for flow control. From your code it is not clear what Exceptions might be thrown. Maybe you can elaborate a bit more.
The Scanner.nextInt() method can throw a few exceptions. The linked page of the API Specifications lists out the three exceptions which can be thrown.
For example, if a non-integer value is entered, such as "one" instead of 1, an InputMismatchException can be thrown.
In general, a try-catch is used to catch exceptions, as illustrated in the following code:
try
{
Integer.parseInt("one"); // Statement that can cause an exception.
}
catch (NumberFormatException e) // Specify which exception to catch.
{
// Code to handle the NumberFormatException.
}
More information about exceptions can be found in Lessons: Exceptions of The Java Tutorials. In particular, the Catching and Handling Exceptions section may be useful.
Adding exceptions in this piece of code does not add much value.
What I can think of is something like this:
public static void main (String [] args){
.....
try{
handleUserChoice(choice);//new method
}
catch(InvalidChoiceException e){
System.out.println("Invalid Option!!!");
}
}
The only part of your code that might possibly throw an exception is the call to:
scan.nextInt();
According to the JavaDocs, this can throw the following possible exceptions:
InputMismatchException (if the next
token does not match the Integer
regular expression, or is out of
range)
NoSuchElementException (if
input is exhausted)
IllegalStateException (if this
scanner is closed)
So if you wanted your code to account for the possibilities of these exceptions being thrown, you should re-write it like so:
try {
choice = scan.nextInt();
}
catch (InputMismatchException e) {
System.out.println(e.getMessage());
}
catch (NoSuchElementException e) {
System.out.println(e.getMessage());
}
catch (IllegalStateException e) {
System.out.println(e.getMessage());
}
Generally, you want your "catch" blocks to start out specific or very likely to happen to less likely / more general in nature.
You can additionally "throw" the exceptions so that whatever method the exception occurs in doesn't handle it-- the method which called that exception-causing method would have to handle it (or throw it again, etc, until it gets to the Java runtime).
In the event it's the "if" statement you wish to replace, I'd recommend the "switch" statement:
switch (choice) {
case 1: N95.loadDeduct(load);
break;
case 2: N95.loadDeduct(load, greet);
break;
default: System.out.println("Invalid Option!!!");
}
I don't see any reason to use exceptions instead of the if-else block. you could try using a switch statement, it'd look better.
you should use exceptions to handle errors that might occur inside the methods loadDeduct. then you would surround the lines calling N95.loadDeduct with a try-catch block, to write what would happen if loadDeduct went wrong.
It's really pretty simple. First identify where you want an exceptioon. There can be exceptinos thrown by library code or you can throw your own. Then use a try .. catch to handle it. Here's a simple "hello, world" ish example:
public class TryTry {
public void doIt() throws Exception {
System.err.println("In the doIt method.");
throw new Exception("Hello there!");
}
public static void main(String[] argv){
TryTry t = new TryTry();
// here we'll catch it.
try {
System.err.println("About to call doIt().");
t.doIt();
} catch (Exception e) { // e now has your exception object
System.err.println("In the exception handler.");
System.err.println("Exception says: "+ e);
}
}
}
The effect of throw is to construct that exception object and send it up the stack until it's caught. To catch it, you surround the code that might throw it with tr { ... }, and handle the exception with catch.
Here's the results:
javac TryTry.java && java TryTry
About to call doIt().
In the doIt method.
In the exception handler.
Exception says: java.lang.Exception: Hello there!

Categories