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()
Related
I wanted to consult about JDK code exception handling,
In ScriptEngineManager from lines 120 there are unused secondary catch for ServiceConfigurationError which can't be thrown as I understand it
try {
while (itr.hasNext()) {
try {
ScriptEngineFactory fact = (ScriptEngineFactory) itr.next();
facList.add(fact);
} catch (ServiceConfigurationError err) {
System.err.println("ScriptEngineManager providers.next(): "
+ err.getMessage());
if (DEBUG) {
err.printStackTrace();
}
// one factory failed, but check other factories...
continue;
}
}
} catch (ServiceConfigurationError err) {
System.err.println("ScriptEngineManager providers.hasNext(): "
+ err.getMessage());
Is there a reason why a second catch will be necessary? it seems it effect only while (itr.hasNext()) which doesn't throw any exception
Or is it just overly cautious to ensure method not throwing exception in any case, as commented
// do not throw any exception here.
Actually java allows you to duplicate such try-catch without any error/warning:
try {
try {
ScriptEngineFactory fact = itr.next();
engineSpis.add(fact);
} catch (ServiceConfigurationError err) {
err.printStackTrace();
}
} catch (ServiceConfigurationError err) {
err.printStackTrace();
}
If I'll concatenate catches in same try I would get compilation error
Unreachable catch block for ServiceConfigurationError. It is already handled by the catch block for ServiceConfigurationError
Minor misconception: the second catch does not only cover the while loop. It would also take care about such exceptions thrown from within the first catch block.
But you are correct: that catch block, as well as the loop "header" should not throw such an exception. It seems rather odd that simply iterating an iterator needs "protection" in such a way.
Thus: maybe this is a leftover when other code existed in that method. Or it is overdoing. Or worst case, the code that we don't see (that creates that iterator) can in fact throwing that kind of error. Which, as said, would be odd and a very bizarre design, to say the least.
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 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
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.