자바 질문이요.
조회수 2544회
-
(•́ ✖ •̀)
알 수 없는 사용자
1 답변
-
반복문 안에서 try catch 를 구현하고 catch 절에서 continue 로 처리해도 되며 반복문안에서 예외이므로 오류 발생시 다음 반복 처리를 할 것입니다.
아래의 예제는 0부터 10까지의 배열을 만들고 그 요소들로 10을 나눕니다.
의도적으로 0을 넣어서 ArithmeticException 예외(오류)가 발생하도록 했습니다.
각 차이점을 확인해보세요.
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
댓글 입력