Java Try and catch - java

I have a java program that is supposed to handle an Exception, but the end result is far from what I intended it to be. Here is the overall idea of my program: it is supposed accept an input of zero and exit the program. The input dialog should cause an Exception which should be caught and print the message "bad number".
My brain is telling me I'm missing one line of code in the catch block.
here is my code:
import javax.swing.JOptionPane;
public class exceptTest {
public static void main(String[] args){
try {
String line = JOptionPane.showInputDialog(null, "enter number");
if(line.equals ("0"));
System.exit(0);
}catch(Exception e){
JOptionPane.showMessageDialog(null, "bad number");
}
}
}

You are not catching an exception here, you are simply making a if statement, you can just use an if/else.
try{
String line = JOptionPane.showInputDialog(null, "enter number");
if(line.equals ("0")){
System.exit(0);
}else{
JOptionPane.showMessageDialog(null, "bad number");
}
}catch (Exception ex){
ex.printStackTrace();
}
The catch you would only use for any exceptions showInputDialog() throws, but for your number check you are not catching anything, it just simply is not 0.

You don't execute your exception handling code because you never throw an exception. The code will execute the input, then test the input to be equal to "0", then based on that will or will not display a dialog, and then it will execute.
The throwing of an exception occurs either because something has happened outside the conditions that the code will handle, or because you throw one explicitly.
By "outside the conditions" etc., I mean something like dividing by 0. Java (nor any other language) will handle that, and an exception will be thrown. The normal steps of procedural processing will stop, and an execution handler will be called.
In your case, if you (for instance) attempted to parse the input to be a number, but the input was not a number, you would get an exception. This is different functionality than you say you wanted, but is a better illustration of what an exception is for. Something like
try
{
int numberEntered = Integer.parse(line);
JOptionPane.showMessageDialog(null, "Entered a number, parsed to " + numberEntered);
}
catch (NumberFormatException nfe)
{
JOptionPane.showMessageDialog(null, "Did not enter a number, but <" + line + ">");
}
shows the sort of thing exceptions are normally good for.
If you wanted to, you could define an exception, call it BadNumberException, and throw it in the code you have -- you would put it (I guess) in an else clause for your if statement. But your routine would be throwing the exception, and I think it is unusual for the routine that throws an exception to also catch it.
Hope that helps.
rc

You have a semi-colon after your if statement, it terminates the line and the compiler does not look for the rest of the if. Remove your semi-colon and it will work fine.
import javax.swing.JOptionPane;
public class exceptTest
{
public static void main(String[] args){
try
{
String line = JOptionPane.showInputDialog(null, "enter number");
if(line.equals ("0")) //semi-colon removed here
{
System.exit(0);
}
throw new IllegalArgumentException("Input was not 0");
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, "bad number");
}
}
}

Your code does not throw an exception if the input is not equal to 0. Therefore, you never catch anything, thus no errormessage is shown on the screen.
You could do two things:
- throw an exception if the input is not 0 (then you will enter the catch)
or
- use an else with your if that displays the error message (then you don't need the try-catch for checking whether the input is 0)
Edit: And of course as Hunter McMillen noticed, you need to remove the semicolon after your if statement.

Related

How to properly use Exception method getMessage

I have the following java code:
System.out.print("\fPlease Enter an integer: ");
while(!validInt){
try{
number = kb.nextInt();
validInt = true;
}catch(InputMismatchException e){
System.out.print("Pretty please enter an int: ");
System.out.print(e.getMessage());
kb.nextLine();
continue;
)
kb.nextLine();
}
how can I set e.getMessage() so that System.out.println(e.getMessage()) will print "Pretty please enter an int: "
You only set the message when the exception is created, it's an argument to the constructor. In your case it would have been nice if the InputMismatchException was created like this:
tnrow new InputMismatchException("Pretty please enter an int: ")
Since you probably aren't creating the InputMismatchException, you can't set it's message, however inside a catch you can do something liket this:
catch(InputMismatchException ime){
throw new IllegalArgumentException("Pretty please enter an int: ");
}
Then someone above you can catch that exception and will have an appropriate error message.
This is obviously a bit awkward which is why it usually isn't used this way.
Note:
You aren't usually supposed to re-use java exceptions but create your own. This is pretty annoying and I almost always re-use either IllegalArgumentException or IllegalStateException Because those are good, reusable exceptions and describe most of the reasons you'd want to throw in general code for "Catch and rethrow" exceptions as I discussed above.

Catch block in Java code gets executed even when the try block satisfies the mentioned condition?

I am new to Java and I tried to use exceptions in my Java code to give the user an alert if in case he/she types a negative number or a non-numerical value in the text field. But still, when I enter a single-digit positive number, the catch blocks get executed.
//textfield to enter the amount of Rs.
txt_rupees = new JTextField();
//KeyListener to check if the content entered in the text field is a number or not.
txt_rupees.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
try {
//convert the user input in the textfield from string to double
double check = Double.parseDouble(txt_rupees.getText());
//checking if the number entered by the user is positive or not.
if (check > 0) {
lb_check1.setText(" ");
}
else {
lb_check1.setText("Please enter a valid number");
}
}
catch (NumberFormatException ne){
//If the user enters a non-numerical character then this message should be displayed by the label.
lb_check1.setText("ALERT: Please enter a valid float or int value in the textfield");
}
}
});
To understand how try-catch block work, I will give an example.
class InsufficientMoneyException extends Exception{
InsufficientMoneyException(int money){
System.out.println("You only have $"+money);
}
}
class A throws InsufficientMoneyException{
try{
int money = 100;
if(money<1000) throw new InsufficientMoneyException(money);
System.out.println("I am NOT being executed!");
} catch (InsufficientMoneyException e){System.out.println("I am being executed!");}
}
Code block will get executed unless it encounters a statement that tells it to throw a exception. After throwing the exception, the catch will catch the exception and the catch block will get executed.
In your case,
double check = Double.parseDouble(txt_rupees.getText());
The library function parseDouble() will throw the NumberFormatException so the lines in try block after this line, won't get executed.

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 ;)");
}

Continue Android app after checked exception is thrown

So I'm trying to parse an numeric input in my EditText box. I'm using Integer parse to parse input into int.
#Override
public void afterTextChanged(Editable s) {
int temp;
try{
temp=Integer.parseInt(s.toString());
//do something
}catch (NumberFormatException e){
temp=someOtherNumber;
}
}
I want to continue app even if user entered invalid number.
Is that possible?
Yes this is possible. Put only catch able code in try catch block. write your remaining code after above catch block.
NumberFormatException you should put when you are confident enough that
1.) Editable s, s is not null. // if not - use Exception class here
If that ius not the case, then catching more prcise exception ie. NumberFormatException is enough. you have already put a catch block, so exception will not be propagated, and you can still continue with your app.
basic Structure
try{
// do your stuff here 1
}catch(NumberFormatException nfe){
// do your stuff here 2
}
// do your stuff here 3
Either do your stuff at 1 and 2 both or just at 3
First check for Editable s it should not null then go further., If you want to catch any exception other than NumberformatException.
then change Catch(NumberFormatException e) to this catch (Exception e). If you have any query please let know.

Java Catch Exception - Empty String

I'm looking for an exception on how to catch an invalid String that is user input. I have the following code for a exception on an integer input:
try {
price = Integer.parseInt(priceField.getText());
}
catch (NumberFormatException exception) {
System.out.println("price error");
priceField.setText("");
break;
But I'm not aware of a specific exception for strings, the input is a simple JTextBox so the only incorrect input I can think of is if the user enters nothing into the box, which is what I'm looking to catch.
if (textField.getText().isEmpty())
is all you need.
Or maybe
if (textField.getText().trim().isEmpty())
if you also want to test for blank inputs, containing only white spaces/tabs.
You generally don't use exceptions to test values. Testing if a string represents an integer is an exception to the rule, because there is no available isInt() method in String.
You can do like
if (priceField.getText().isEmpty())
throw new Exception("priceField is not entered.");
You could check if priceField contains a string by using this:
JTextField priceField;
int price;
try {
// Check whether priceField.getText()'s length equals 0
if(priceField.getText().getLength()==0) {
throw new Exception();
}
// If not, check if it is a number and if so set price
price = Integer.parseInt(priceField.getText());
} catch(Exception e) {
// Either priceField's value's length equals 0 or
// priceField's value is not a number
// Output error, reset priceField and break the code
System.err.println("Price error, is the field a number and not empty?");
priceField.setText("");
break;
}
When the if-statement is true (If the length of priceField.getText() is 0) an exception gets thrown, which will trigger the catch-block, give an error, reset priceField and break the code.
If the if-statement is false though (If the length of priceField.getText() is greater or lower than 0) it will check if priceField.getText() is a number and if so it sets price to that value. If it not a number, a NumberFormatException gets thrown, which will trigger the catch-block etc.
Let me know if it works.
Happy coding :) -Charlie
if you want your exception to be thrown during the normal operation of the Java Virtual Machine, then you can use this
if (priceField.getText().isEmpty())
throw new RunTimeException("priceField is not entered.");

Categories

Resources