Programing

Catch없이 Java Try Catch 최종적으로 차단

lottogame 2020. 7. 18. 10:27
반응형

Catch없이 Java Try Catch 최종적으로 차단


새로운 코드를 검토하고 있습니다. 프로그램에는 try 및 finally 블록 만 있습니다. catch 블록이 제외되었으므로 try 블록에 예외 또는 던질 수있는 것이 있으면 어떻게 작동합니까? finally 블록으로 바로 이동합니까?


try 블록의 코드 중 하나라도 검사 된 예외를 throw 할 수 있으면 메소드 서명의 throws 절에 나타나야합니다. 확인되지 않은 예외가 발생하면 메소드에서 버블 링됩니다.

finally 블록은 예외 발생 여부에 관계없이 항상 실행됩니다.


에 작은 노트 try/ finally: 최종적으로 항상하지 않는 한 실행됩니다

  • System.exit() 호출됩니다.
  • JVM이 충돌합니다.
  • try{}블록 결코 끝 (예를 들면 무한 루프).

Java 언어 사양 (1)try-catch-finally 은 실행 방법을 설명합니다 . 캐치가없는 것은 주어진 Throwable을 캐치 ​​할 수없는 것과 같습니다.

  • 값 V가 발생하여 try 블록의 실행이 갑자기 완료되면 다음을 선택할 수 있습니다.
    • V의 런타임 유형이 try 문의 catch 절 매개 변수에 지정 가능한 경우
      ……
    • V의 런타임 유형을 try 문의 catch 절 매개 변수에 지정할 수없는 경우 finally 블록이 실행 됩니다. 그런 다음 선택이 있습니다.
      • finally 블록이 정상적으로 완료되면 값 V가 throw되어 try 문이 갑자기 완료됩니다.
      • 이유 S에 대해 finally 블록이 갑자기 완료되면 이유 S에 대해 try 문이 갑자기 완료됩니다 (값 V의 throw는 버려지고 잊혀짐).

(1) try-catch-finally의 실행


내부는 마지막으로 예외를 외부 블록에 던지기 전에 실행됩니다.

public class TryCatchFinally {

  public static void main(String[] args) throws Exception {

    try{
        System.out.println('A');
        try{
            System.out.println('B');
            throw new Exception("threw exception in B");
        }
        finally
        {
            System.out.println('X');
        }
        //any code here in the first try block 
        //is unreachable if an exception occurs in the second try block
    }
    catch(Exception e)
    {
        System.out.println('Y');
    }
    finally
    {
        System.out.println('Z');
    }
  }
}

결과

A
B
X
Y
Z

finally 블록은 try 블록이 끝난 후에 항상 실행됩니다. 예외로 인해 try가 정상적으로 또는 비정상적으로 종료 될 수 있습니다.

try 블록 내의 코드에서 예외가 발생하면 현재 메소드는 단순히 finally 블록을 실행 한 후 동일한 예외를 다시 발생 (또는 계속 발생)합니다.

If the finally block throws an exception / error / throwable, and there is already a pending throwable, it gets ugly. Quite frankly, I forget exactly what happens (so much for my certification years ago). I think both throwables get linked together, but there is some special voodoo you have to do (i.e. - a method call I would have to look up) to get the original problem before the "finally" barfed, er, threw up.

Incidentally, try/finally is a pretty common thing to do for resource management, since java has no destructors.

E.g. -

r = new LeakyThing();
try { useResource( r); }
finally { r.release(); }  // close, destroy, etc

"Finally", one more tip: if you do bother to put in a catch, either catch specific (expected) throwable subclasses, or just catch "Throwable", not "Exception", for a general catch-all error trap. Too many problems, such as reflection goofs, throw "Errors", rather than "Exceptions", and those will slip right by any "catch all" coded as:

catch ( Exception e) ...  // doesn't really catch *all*, eh?

do this instead:

catch ( Throwable t) ...

Java versions before version 7 allow for these three combinations of try-catch-finally...

try - catch
try - catch - finally
try - finally

finally block will be always executed no matter of what's going on in the try or/and catch block. so if there is no catch block, the exception won't be handled here.

However, you will still need an exception handler somewhere in your code - unless you want your application to crash completely of course. It depends on the architecture of your application exactly where that handler is.

  • Java try block must be followed by either catch or finally block.
  • For each try block there can be zero or more catch blocks, but only one finally block.
  • The finally block will not be executed if program exits(either by calling System.exit() or by causing a fatal error that causes the process to abort).

how does the try block work if it encounters an exception or anything throwable

The exception is thrown out of the block, just as in any other case where it's not caught.

The finally block is executed regardless of how the try block is exited -- regardless whether there are any catches at all, regardless of whether there is a matching catch.

The catch blocks and the finally are orthogonal parts of the try block. You can have either or both. With Java 7, you'll be able to have neither!


Don't you try it with that program? It'll goto finally block and executing the finally block, but, the exception won't be handled. But, that exception can be overruled in the finally block!


The finally block is executed after the try block completes. If something is thrown inside the try block when it leaves the finally block is executed.


Inside try block we write codes that can throw an exception. The catch block is where we handle the exception. The finally block is always executed no matter whether exception occurs or not.

Now if we have try-finally block instead of try-catch-finally block then the exception will not be handled and after the try block instead of control going to catch block it will go to finally block. We can use try-finally block when we want to do nothing with the exception.

참고URL : https://stackoverflow.com/questions/4559661/java-try-catch-finally-blocks-without-catch

반응형