Java question.

Asked 2 years ago, Updated 2 years ago, 23 views

I'm reading a text file Read by line.

But if you can't read the text in the next line,

If an error occurs

I want to move on to the next line.

What should I do?

Should I say exception?

java

2022-09-21 18:36

1 Answers

Try catch can be implemented in the repeat statement and processed as continue in the catch clause, except in the repeat statement, so if an error occurs, we will do the next repeat process.

The example below creates an array from 0 to 10 and divides the elements by 10.

Intentionally zeroed in to cause an ArithmeticException exception (error).

Check out each difference.

jshell> int[] numbers = IntStream.rangeClosed(0, 10).toArray()
numbers ==> int[11] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }
jshell> for(int i:numbers){
   ...> try{ 
    int z = 10/i;
    System.out.println(z);
}catch(Exception e){
    e.printStackTrace();
}
   ...> }
java.lang.ArithmeticException: / by zero
    at REPL.$JShell$13.do_it$($JShell$13.java:6)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:564)
    at jdk.jshell/jdk.jshell.execution.DirectExecutionControl.invoke(DirectExecutionControl.java:209)
    at jdk.jshell/jdk.jshell.execution.RemoteExecutionControl.invoke(RemoteExecutionControl.java:116)
    at jdk.jshell/jdk.jshell.execution.DirectExecutionControl.invoke(DirectExecutionControl.java:119)
    at jdk.jshell/jdk.jshell.execution.ExecutionControlForwarder.processCommand(ExecutionControlForwarder.java:134)
    at jdk.jshell/jdk.jshell.execution.ExecutionControlForwarder.commandLoop(ExecutionControlForwarder.java:225)
    at jdk.jshell/jdk.jshell.execution.Util.forwardExecutionControl(Util.java:76)
    at jdk.jshell/jdk.jshell.execution.Util.forwardExecutionControlAndIO(Util.java:137)
    at jdk.jshell/jdk.jshell.execution.RemoteExecutionControl.main(RemoteExecutionControl.java:70)
10
5
3
2
2
1
1
1
1
1

jshell> for(int i:numbers){
   ...> try{ 
    int z = 10/i; 
    System.out.println(z);
}catch(Exception e){continue;}
}
10
5
3
2
2
1
1
1
1
1


2022-09-21 18:36

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.