I have a try-catch block as defined below and a for-each loop inside it.
try
{
// Doing some JDBC Connections here
Map<String,Connection> connections = new HashMap<>();
while(DeviceRS.next()){
final String ip_address = DeviceRS.getString("Connection_vch");
System.out.println("Value of the IP Address Field:"+ip_address);
connections.put(ip_address,DriverManager.getConnection("jdbc:mysql://" + ip_address + ":3306/test",RemoteUser,RemotePass));
}
for(final String ip : connections.keySet())
{
// Selecting and inserting into database here ...
}// ENd of for loop
}// ENd of try block
catch(SQLException ex){
ex.printStackTrace();
}
So, if something goes wrong with the connection, my program will get stuck in the catch block,printing the stack trace. I want to move onto other connections.
Is there a way can exit the catch block quickly just after printing the stack trace?
Note: I haven't mentioned full code here as I think my question is not concerned with my code.
Changed your code like this. To quickly skip it on its failure.
// Doing some JDBC Connections here
Map<String,Connection> connections = new HashMap<>();
try
{
while(DeviceRS.next()){
try{
final String ip_address = DeviceRS.getString("Connection_vch");
connections.put(ip_address,DriverManager.getConnection("jdbc:mysql://" + ip_address + ":3306/test",RemoteUser,RemotePass));
}
catch(SQLException ex){
ex.printStackTrace();
}
}
catch(Exception ex){
ex.printStackTrace();
System.out.println("in catch block");
//System.exit(0); // dont use this -in real time projects
}finally{
System.out.println("in finally block");
}
for(final String ip : connections.keySet())
{
// Selecting and inserting into database here ...
}// ENd of for loop
}// ENd of try block
I don't think there's fine looking way. But you can make another try-catch block inside your try-catch
try {
// your code here
for(final String ip : connections.keySet()) {
try { // inner catch
// your code, that will be continued if sql exception occurs
} catch (SQLException e) {
e.printStackTrace();
}
}
} catch (SQLException e) {
e.printStackTrace();
}
Like you said if you want if something goes wrong with the connection and you want to move onto another connection,just do this :
boolean check = true;
while(check) {
try {
Map<String,Connection> connections = new HashMap<>();
while(DeviceRS.next()){
final String ip_address = DeviceRS.getString("Connection_vch");
connections.put(ip_address,DriverManager.getConnection("jdbc:mysql://" + ip_address + ":3306/test",RemoteUser,RemotePass));
} // Ends inner while
check = false; //As connection is ok,we don't need to loop back.
for(final String ip : connections.keySet())
{
// Selecting and inserting into database here ...
}
}// Ends try block
catch(SQLException ex){
ex.printStackTrace();
} //Ends catch block
finally{
// close the connection if needed.
} // Ends finally block
}// Ends outer while loop
Related
How to continue the iteration loop if an exception occurs at while (iterator.hasNext())?
So I want to do something like below.
try {
loop: while (iterator.hasNext()) // as excetion is on this line excetion will be catch by catch_2
{
try {
Result res = (Result) iterator.next();
list.add(res);
} catch (Exception e) { // catch_1
e.printStackTrace();
}
}
} catch (Exception e) { // catch_2
// goto start of the loop
continue loop;
}
Iterator<UserProvisioning> iterator = beans.iterator();
while (iterator.hasNext()) {
try {
UserProvisioning userProvisioning = (UserProvisioning) iterator.next();
System.out.println(userProvisioning.getFIRST_NAME());
list.add(userProvisioning);
} catch (Exception e) {
// TODO Auto-generated catch block
logger.error("Error occured...)
}
}
As per my understanding iterator.hasNext() tries to check whether next element is present or not by mapping csv record column to POJO fields and as there is invalid data in csv record headers count do not matches record files hence error
java.lang.RuntimeException: com.opencsv.exceptions.CsvRequiredFieldEmptyException: Number of data fields does not match number of headers.
SO I am trying to log the error and continue to iterate next records.
EDIT
iterator.hasNext() should return true or false but its throwing error
If you put a try-catch block within your loop it will continue the loop to the end unless you break out of it
for(Iterator<UserProvisioning> iter = beans.iterator(); iter.hasNext();) {
try{
UserProvisioning userProvisioning = iter.next();
System.out.println(userProvisioning.getFIRST_NAME());
list.add(userProvisioning);
} catch(Exception ex) {
logger.warn("An issue occurred when looping through user provisionings: " + ex.getMessage());
}
}
The above code will setup an iterator and loop through it. If an exception occurs it will log and continue the loop since no break was called.
also since you tell what type the iterator is, there is no need to cast it when you call iter.next()
I put the declaration in the while loop, and the program would not running and also does not return any error. I suspect the while loop become an infinite loop.
try
{
while (true)
{
inputStream = new ObjectInputStream (new FileInputStream (fileName));
Ship copyObject = (Ship) inputStream.readObject();
String nameCompany = copyObject.getCompanyName();
if (compName.equalsIgnoreCase(nameCompany)){
listShipName += (copyObject.getShipName() + ", ");
numberOfShip ++;
}
}
}
catch (EOFException e)
{
}
catch (Exception e)
{
e.printStackTrace();
}
But if I put the declaration of input stream out of the while loop, the program runs successfully. Can someone explain why this happens?
try
{
inputStream = new ObjectInputStream (new FileInputStream (fileName));
}
catch (Exception e)
{
e.printStackTrace();
}
try
{
while (true)
{
Ship copyObject = (Ship) inputStream.readObject();
String nameCompany = copyObject.getCompanyName();
if (compName.equalsIgnoreCase(nameCompany)){
listShipName += (copyObject.getShipName() + ", ");
numberOfShip ++;
}
}
}
catch (EOFException e)
{
}
catch (Exception e)
{
e.printStackTrace();
}
You're reopening your file on every iteration through the loop, which means you are only ever reading the first object from the file. But you're reading the same object over and over again.
As well as opening your file only once, you really should try to detect the end of file without throwing an exception. As a matter of style, exceptions should be thrown when things go wrong, not as a matter of course.
Now I realize that in each iteration, I reopen the input stream, so the loop would not reach to the end of the file, and it becomes infinite.
I am running another jar with this code:
(I am updating a gui in some parts , so dont feel confused.)I get an IO Exception (Stream Closed) here:
if((line = readr.readLine()) != null){
Thats the full code:
if(!data.serverStarted()){
try{
data.updateConsole("Starting server!");
String fileDir = data.dir + File.separator + "craftbukkit.jar";
Process proc = Runtime.getRuntime().exec("java -Xmx2048M -jar "+"craftbukkit.jar"+" -o true --nojline");
data.setOutputStream(proc.getOutputStream());
InputStream is = proc.getErrorStream();
}catch(IOException ex){
ex.printStackTrace();
}
BufferedReader readr = new BufferedReader(new InputStreamReader(is));
data.setServerStarted(true);
String line;
while(data.serverStarted()){
try {
if((line = readr.readLine()) != null){
data.updateConsole(line);
}
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
readr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}else{
data.updateConsole("You have already started your server!");
}
You have a while loop that closes readr on every pass. The next time it gets to the try block, readr is closed. Perhaps you intended to put the try/catch block around the while loop?
You are closing the reader inside the loop that reads from it. You need to close it outside of the loop:
try {
String line;
while (data.serverStarted() && ((line = readr.readLine()) != null)) {
try {
data.updateConsole(line);
} catch (IOException e) {
e.printStackTrace();
}
}
} finally {
try {
readr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
I am surprised that this code even compiles.
You declare the actual InputStream is inside the try/catch at the beginning, but that makes it only visible inside that block. So whatever you give to the BufferedReader a few lines below is something else and most likely not what you think it is.
In addition your while(data.serverStarted()) does not check if the stream is still open, and later you only use a single if check (again with no check if the stream is open), so you'll only read one single line at best.
I have a feeling that you had a bad OutOfCoffeeException while writing this code. ;)
folks. I'm trying to write to a file from a stack. The stack was created by reading from another file. I'm using the stack so that I can reverse the file I read in. The file names to read and write to are from the command line.
This is how I have my stack implemented:
while(read.hasNext()) {
stack.push(read.next());}
The code for my other file that the stack is supposed to write to:
FileWriter w = null;
try {
w = new FileWriter(new File(args[1]));
} catch (IOException e) {
e.printStackTrace();
}
if (!stack.isEmpty()) { //this was a while statement
try {
w.write(stack.pop());
} catch (IOException e) {
e.printStackTrace();
}
} else {
System.out.println("Didn't make it.");
}
The problem that I'm having is when I run my program, the file I want to write to is created, but nothing gets written to the file. I originally thought that my stack didn't have anything in it (that's why I changed my while statement to an if; it's temporary). The "Didn't make it." didn't print so I now know it's not that. What am I doing wrong here? Any help is appreciated.
After w.write(stack.pop()); call the fush() method:
w.write(stack.pop());
w.flush();
and you can return the while statement. At the end call w.close();
the method stack.pop returns an Object if you do not specify at the time of declaration like this
Stack<String> stack = new Stack<String>();
and after writing you should use w.flush() and also you should use the w.close.
you should nest the while statement itself into the try block
for instance
try {
while(!stack.isEmpty()) {
w.write(stack.pop()); // assuming you have declared it as Stack<E>
}
w.flush();
w.close();
} catch(IOException e) {
e.printStackTrace();
}
EDIT:
after you are done with FileWriter when you close it, that has to nested inside a try catch block to catch any IOException if thrown. if you use the w.write() method inside the try catch block that is within the while loop then after the while loop iteration is over you have to build another try catch to place w.close()
Sorry if my title is a little bit confusing.
My program is doing some web scraping and thus will catch a few SocketTimeoutException due to random network conditions. Right now when the SocketTimeoutException is caught, that particular loop is skipped, and therefore i will miss some data. I'm sure that everything will be fine when the code in the skipped loop is run again. As I'm scraping a huge amount of data ( > 1 million sets of numbers ), I don't want to record the exceptional loops and ran them again manually. Is there any way to run the same loop again when catch an exception?
try{
for(){
someCode
...
}
}catch(IOException){
}
Just put the try-catch inside the loop
for () {
try {
// somecode
// ..
} catch ( IOException ioException ) {
// handle
}
}
Why not put the exception handling inside the loop
for(){
try{
// someCode
}catch(IOException e){
//handle exception if necessary
}
}
You must be doing this. Do try catch inside the loop.
for(){
try {
someCode
...
} catch(IOException){
}
}
This has a problem,
try{
for(){
// someCode
...
}
}catch(IOException){
// Once exception happens your for() loop breaks !!!!!
}
Instead, do this...
for () {
try {
// somecode
// ..
} catch ( IOException ioException ) {
// handle(do something) here, not throwing error which will break the loop
}
}
I you want to redo the same loop iteration:
int i = 0;
int n = 15; // your n
for (i = 0; i < n; i++) {
try {
// some code
} catch (Exception e) {
i--;
}
}
But be careful of an infinite looping! You should add a MAX_TRIES management.