Try catch exception (letter in int) - java

I'm trying to use a try catch structure to show an error when I try to input a letter into a string. Which exception should I be using for this? the console shows me InputMismatchException but this does not work.
input that works:
beginnen = 1
input that doesn't work:
beginnen = a
it obviously doesn't work cause i'm putting a string into an int, I just want to have a message show up when this occurs
int beginnen;
String error = "Something went wrong";
try {
beginnen = Input.readInt();
}
catch (InputMismatchException IME) {
System.out.println(error);
}
error that shows up:
Exception in thread "main" java.util.InputMismatchException

If the documentation is foggy, use experiment:
try {
beginnen = Input.readInt();
} catch (Throwable x) {
System.err.println("Catched "+x.getClass().getName());
}
This will print the exact class name for you and you can later change your code to catch the exception of this class. This will also show for you, maybe just nothing is actually thrown.

Your Try/Catch expression looks fine to me, however you've mistakenly referenced error, which is not defined anywhere.
Try changing it to System.out.println(IME.getMessage());

Related

Get a custom error message, instead of 500

I have a service that looks like this:
public String storeTestRequest(Map<String, String> data, HttpSession session) {
JSONObject json = new JSONObject(data);
boolean hasHealthInsurance = json.getAsString("hasHealthInsurance").equals("true");
try {
this.testRequestRepository.save(new TestRequest(
json.getAsString("firstname"),
json.getAsString("surname"),
json.getAsString("street"),
hasHealthInsurance
));
return "All good.";
}
catch (Exception e) {
return "Something went wrong.";
}
}
In this example, I am saving the values of 4 fields but in fact there are much more and I don't want to validate any of them. So if all values could be saved successfully, I should get the message All good. But if some values are missing, I should get the message Something went wrong..
I have tried it with try & catch but I still get a 500 error.
Your hasHealthInsurance property is empty or null. Your exception message says it's caused by this line.
boolean hasHealthInsurance = json.getAsString("hasHealthInsurance").equals("true");
If you put this line in your try catch block, you will see the exception message in the catch block.

Java: try/catch with InputMismatchException creates infinite loop while reading of a file

I have a task to make a program that will add up all the valid integers in a file and to ignore anything that isn’t a valid int. I have to use Try and Catch.
File Numbers = new File("Numbers.txt");
Scanner readFile = null;
int i = 0;
int total= 0;
boolean success = false;
while(!success){
try {
readFile = new Scanner(Numbers);
while(readFile.hasNext()){
i = readFile.nextInt();
System.out.println(i);
total = i + total;
};
success = true;// Ends The loop
} catch (FileNotFoundException e1) {
System.err.println(Numbers.getName()+" does not exist");
}
catch(InputMismatchException e2){
System.err.println("Data incorrect type expecting an int found: " + readFile.nextLine());
readFile.next();
}
System.out.println("total is: " + total);
};
The problem is that the program gets caught in an infinite loop, where instead of going past the exception it just starts again.The task seems pretty straight forward, yet i don't know why it wont work?
You fall into infinite loop because when exception happens, the success variable didn't change its value to true. In order to do some action even when exception happens you should add the finnaly block. It could look like this:
try {
// do some stuff
} catch (Exception e) {
// catch the exception
} finally {
if (!readFile.hasNext()) success = true;
}
And by the way, never do this: catch (Exception e), I did it just for example sake. Instead always catch the specific exception. Because Exception is the most basic class in the exception hierarchy, so it will catch up all the exceptions, and unless you re-throw it you could have false feeling of "safiness". When you want to catch all the exceptions, you should do this:
try {
// do stuff
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
e.printStackTrace(); // or other approptiate action, i.e. log it.
}
Assume any of the following FileNotFound or InputMismatchException exceptions will raise, then your program wont change success to true. Thus it returns to the outer while loop and read the same file. Because nothing has changed the same Exception will be thrown again.
==> Endless loop.
To fix that I suggest to move the try/catch block to the inner while.

Multiple catch statements with the same exception types

I've been looking all over for an answer to this and have yet to find one.
Basically I am trying to connect to a database server through a GUI. My boss wants to be able to enter all fields and then check to see if they are valid entries, then if there are any invalid entries, he wants me to turn the text red, indicating that the field is invalid. I have the try statement catch ClassNotFoundException and SQLException. Because there are multiple fields that need to be checked, I have tried to have a set of if statements to check the connection info. Here is the code below, I hope this makes sense...
//The cancel boolean values in this code are used elsewhere to regulate the Threads
try
{
//attempt connection here
}
catch(ClassNotFoundException | SQLException e)
{
String[] errors = new String[4]; //This will create a String array of the errors it catches
//and will later get called into a method that displays
//the messages in a JOptionPane.showMessageDialog()
if (e.getMessage().startsWith("The TCP/IP connection to the host"))
{
errors[0] = "SQL CONNECTION FAILED: Please check the server URL you entered to make sure it is correct.";
cancel = true;
mGUI.serverNameTextField.setForeground(Color.RED);
}
if (e.getMessage().startsWith("Login failed for user"))
{
errors[1] = "LOGIN FAILED: You do not have sufficient access to the server.";
cancel = true;
}
if (e.getMessage().startsWith("Cannot open database"))
{
errors[2] = "SQL CONNECTION FAILED: Please check the database name you entered to make sure it is correct.";
cancel = true;
mGUI.dbNameTextField.setForeground(Color.RED);
}
mGUI.reportErrors(errors); //Method where it reports the String[] array of errors
//However, the 'errors' parameter only returns one error
//message at a time, which is the problem.
Thanks for any help!
****EDIT******
I found a solution, so hopefully this will help someone. I changed my if statements to add an AND argument checking for the specific error code. You find find the error code by either setting a break point and looking at the debug perspective, or you can do what I did and set a print statement to see the error code. Here is the print statement:
System.out.println(((SQLException) e).getErrorCode());
Here are my new for statements:
try
{
//attempt connection here
}
catch(SQLException | ClassNotFoundException e)
{
if (e instanceof SQLServerException && ((SQLServerException) e).getErrorCode() == 0)
{
//code here
}
else{
//code here
}
System.out.println(((SQLException) e).getErrorCode()); //Here is the print statement to see the error code.
if (e instanceof SQLServerException && ((SQLServerException) e).getErrorCode() == 4060)
{
//code here
}else{
//code here
}
if(cancel != true)
{
//code here
}
}
You can do it in multiple ways
1 having more than one catch with a common function
}catch (ClassNotFoundException e){
handleError(e);
}catch (SQLException e){
handleError(e);
}
where handleError takes the exception as the argument.
You dont seem to do anything else so you can just combine them both into a single exception
}catch(Exception e){
}
which will catch everything but you have MUCH less control over the error handling.
A general principle of exceptions is that they are handled at the point they are best abled to be handled.
You seem to have very disparate exceptions and presumably a TCP exception thrown somewhere in the code is not the same as the SQLException thrown when connecting to a database (I might be wrong here since I don't know what the rest of the code looks like). So would not a set of exception handlers, one for each type make more sense. Also to reite from Bryan Roach, text disambiguation is not a good idea.
try {
...
} catch (java.net.SocketException e) {
e[0] = "tcp error";
} catch (java.sql.SQLException e) {
e[1] = "sql exception happened";
}
Also your string array seems a bit risk, possibly a
ArrayList errors = new ArrayList();
errors.add("Some tcp error");
errors.add("Some db error");
and then for you error reporting
mGUI.reportErrors(errors.toArray())
would preserve your interface and not waste you having to allocate extra elements to the array and have empty entries. I don't know exactly what your question is, but you allude to the GUI not displaying multiple errors. Possibly there is a check which stops at the first empty element in an array. Say e[2] and e[4] is populated, it might stop when it iterates over the errors as e[3] is empty. I'm presuming again since I don't know what that code looks like
From the comments above it sounds like what you want to do is have different logic for the various Exception types you are catching within a single catch block. If this is the case, you could go:
...
catch(ClassNotFoundException | SQLException e) {
String[] errors = new String[4];
if (e instanceof ClassNotFoundException) {
//do something here
}
if (e instanceof SQLException) {
//do something else here
}
...etc
}
This should work, but it's probably just as easy to use multiple catch blocks as others have suggested:
}catch (ClassNotFoundException e){
handleError(e);
}catch (SQLException e){
handleError(e);
}
I don't mean any offense, but the way the code handles exceptions might cause some headaches down the road. For example:
if (e.getMessage().startsWith("Cannot open database")) {
Here the code relies on the supporting library that throws the exception to use the same text description, but this description might change if you switch to another JVM version, use a different database driver, etc. It might be safer to go by the exception type, rather than the exception description.

Java try and catch error

I am trying to try and catch an error in my method to write the contents of change drawer to a html document. The error, java.io.FileNotFoundException, appears when the file does not exist. The code below should do this but it comes up with the error "PartB is an incompatible type". I think there is an error in my try and catch code, this the first one I've written and I am at a loss as to why it won't work. Any help would be great. Thankyou.
...
public static void writeHtmlFile()
{
try {
BufferedReader in = new BufferedReader((new FileReader("changedrawer.html")));
String sLine;
StringBuilder sb = new StringBuilder();
while ((sLine = in.readLine()) !=null)
sb.append(sLine+"\n");
//Close file
in.close();
//Output on console
System.out.println(sb.toString());
}
catch (PartB FileNotFoundException) //Why is PartB an incompatible type? (PartB is the name
of the class)
{ System.out.println ("error");
}
...
The syntax for a simple "catch" clause is roughly as follows:
} catch (<exception-type> <identifier>) {
<optional-statements>
}
The <exception-type> is the name if the exception you are trying to catch, and <identifier> is the name of a local variable that you are declaring to hold the exception instance that you just caught.
In your cause, it should look like this:
catch (FileNotFoundExceptio ex) {
System.out.println ("error");
}
... though I'd recommend a more informative error message!
(Note that you have to declare a local identifier, even if you are not going to use it. But it is only a couple of characters, especialy if you use the conventional names e or ex.)
You need to write it as FileNotFoundException PartB, not PartB FileNotFoundException because FileNotFoundException is the type.
You declare an exception like you declare any object or variable:
Exception_Type identifier

How to throw exception for statment?

HI !
I want to throw exception for the line
BarcodeNo=Long.parseLong(jTextField1.getText())
I done this in a way
BarcodeNo=Long.parseLong(jTextField1.getText()) throw new NumberFormatException("Enter Numbers Only ");
But this way compiler throws error stating ";" required
So anyone can tell me how to do this ?
Thanks
That will already thrown an exception if the text isn't in the right format. If you want to change the exception message, you'd have to catch the exception and throw a new one:
try {
BarcodeNo = Long.parseLong(jTextField1.getText());
} catch (NumberFormatException e) {
throw new NumberFormatException("Enter Numbers Only");
}
I wouldn't suggest that you try to use exception message as user-visible messages though - they're more reasonable for logging than for showing an end user.
yes you should put
try
{
BarcodeNo=Long.parseLong(jTextField1.getText());
}
catch(Exception e)
{
throw new NumberFormatException("Enter Numbers Only ");
}

Categories

Resources