try-finally와 try-catch의 차이점
차이점은 무엇입니까
try {
fooBar();
} finally {
barFoo();
}
과
try {
fooBar();
} catch(Throwable throwable) {
barFoo(throwable); // Does something with throwable, logs it, or handles it.
}
Throwable에 대한 액세스 권한을 제공하기 때문에 두 번째 버전이 더 좋습니다. 두 변형 사이에 논리적 차이나 선호하는 규칙이 있습니까?
또한 finally 절에서 예외에 액세스하는 방법이 있습니까?
다음은 두 가지입니다.
- catch 블록은 try 블록에서 예외가 발생하는 경우에만 실행됩니다.
- finally 블록은 예외가 발생하거나 발생하지 않는 경우 항상 try (-catch) 블록 다음에 실행됩니다.
귀하의 예에서 세 번째 가능한 구성을 표시하지 않았습니다.
try {
// try to execute this statements...
}
catch( SpecificException e ) {
// if a specific exception was thrown, handle it here
}
// ... more catches for specific exceptions can come here
catch( Exception e ) {
// if a more general exception was thrown, handle it here
}
finally {
// here you can clean things up afterwards
}
그리고 @codeca가 그의 코멘트에서 말했듯이, finally 블록은 예외가 없어도 실행되기 때문에 finally 블록 내에서 예외에 접근 할 수있는 방법이 없습니다.
물론 블록 외부에서 예외를 보유하는 변수를 선언하고 catch 블록 내부에 값을 할당 할 수 있습니다. 나중에 finally 블록 내에서이 변수에 액세스 할 수 있습니다.
Throwable throwable = null;
try {
// do some stuff
}
catch( Throwable e ) {
throwable = e;
}
finally {
if( throwable != null ) {
// handle it
}
}
이것들은 변형이 아니라 근본적으로 다른 것들입니다. finally
실행 항상 , catch
예외가 발생하는 경우에만 사용할 수 있습니다.
마지막으로 catch 블록은 매우 다릅니다.
- catch 블록 내에서 throw 된 예외에 응답 할 수 있습니다. 이 블록 은 처리되지 않은 예외가 있고 유형이 catch 블록의 매개 변수에 지정된 유형과 일치하거나 하위 클래스 인 경우에만 실행됩니다 .
- 마지막으로 예외가 발생했는지 여부에 관계없이 try 및 catch 블록 후에 항상 실행됩니다 .
그래서
try {
//some code
}
catch (ExceptionA) {
// Only gets executed if ExceptionA
// was thrown in try block
}
catch (ExceptionB) {
// Only executed if ExceptionB was thrown in try
// and not handled by first catch block
}
~와 다르다
try {
//some code
}
finally {
// Gets executed whether or not
// an exception was thrown in try block
}
상당히.
If you define a try block you have to define
- one finally block, or
- one or more catch blocks, or
- one or more catch blocks and one finally block
So the following code would be valid too:
try {
//some code
}
catch (ExceptionA) {
// Only gets executed if
// ExceptionA was thrown in try block
}
catch (ExceptionB) {
// Only executed if ExceptionB was thrown in
// try and not handled by first catch block
}
//even more catch blocks
finally {
// Gets executed whether or not an
// exception was thrown in try block
}
try {
statements;
} catch (exceptionType1 e1) { // one or multiple
statements;
} catch (exceptionType2 e2) {
statements;
}
...
} finally { // one or none
statements;
}
- All try statements must include either one catch clause or a finally clause
- It can have a multiple catch clauses but only one finally clause
- During any execution, if any errors occurs, then the Control is transferred to the appropriate Catch block and executes the statements and Finally block is executed.
No Matter what The Finally block is always executed, So in General, Finally block is used, when you have sessions, Database connections or Files or sockets are open, then the code for closing those connections will be placed. This is just to make sure in an application no memory leaks or Any other issues should not occur.
Finally and catch blocks are quite different:
Within the catch block you can respond to the thrown exception. This block is executed only if there is an unhandled exception and the type matches the one or is subclass of the one specified in the catch block's parameter. Finally will be always executed after try and catch blocks whether there is an exception raised or not.
try is used to run a method that may throw an exception
catch is used to "catch" stop that exception
finally is used for any clean up needed from that exception being caught or not
try{
myObject.riskyMethod(); // run a method that may throw an exception
}
catch(Exception ex){
myLogger.log(ex.Message); // "catch" stop that exception
}
finally{
myObject = null; // clean up needed from that exception being caught
}
In My reasearch Finally block is always executed and it is mainly "used for the any open connections to close" and to destroy something that is running unnecessarily.
Finally block is always executed. Catch block is executed only when an exception that matches the blocks parameter is catched.
Even in the first form you could log it in the calling method. So there is no big advantage unless you want to do some special handling right there.
Generally when we use any resources like streams, connections etc.. we have to close them explicitly using finally block. In the program given below we are reading data from a file using FileReader and we are closing it using finally block.
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class ReadData_Demo {
public static void main(String args[]){
FileReader fr=null;
try{
File file=new File("file.txt");
fr = new FileReader(file); char [] a = new char[50];
fr.read(a); // reads the content to the array
for(char c : a)
System.out.print(c); //prints the characters one by one
}catch(IOException e){
e.printStackTrace();
}
finally{
try{
fr.close();
}catch(IOException ex){
ex.printStackTrace();
}
}
}
}
Maybe other guys like me searched for something like this.
Information from this page tutpoint
Try block will hold the statements which are going to raise exception. The catch block will hold the reference thrown from the try block and required messages are generated from catch block. Finally block is also used to close the used resources like io closing,file closing, dB closing.. In Java -9 enhanced try-with resource came up where the resources are declared outside the try..in enchanced try with resource the catch block is mandatory
참고URL : https://stackoverflow.com/questions/2854910/difference-between-try-finally-and-try-catch
'Programing' 카테고리의 다른 글
사용 된 클래스에 대해서만 Font Awesome 최적화 (0) | 2020.09.25 |
---|---|
거대한 파일의 처음 몇 줄을 복사하고 일부 Linux 명령을 사용하여 끝에 텍스트 줄을 추가하는 방법은 무엇입니까? (0) | 2020.09.25 |
파이썬에서 오버로드 된 함수? (0) | 2020.09.25 |
일부 PHP 콘텐츠를 데모하기 위해 github에서 .html 대신 .php 페이지를 게시하는 방법은 무엇입니까? (0) | 2020.09.25 |
base64로 이미지 소스를 설정하는 방법 (0) | 2020.09.25 |