>  기사  >  Java  >  Java 기본 값: 예외 처리 키워드...

Java 기본 값: 예외 처리 키워드...

怪我咯
怪我咯원래의
2017-06-26 11:46:531359검색

Java 언어는 가비지 수집 메커니즘, 메모리 모델, 예외 처리, 강력한 유형 변환, 크로스 플랫폼 등 매우 강력하여 Java 언어를 인기 있게 만든다고 합니다. 오늘 우리는 먼저 Java의 예외 처리 메커니즘에 대해 이야기하겠습니다. try catch finally throw throw 일반적으로 우리는 이 다섯 가지 키워드를 과소평가하는 것 같습니다. 애플리케이션 시스템을 개발할 때 우수한 예외 처리는 시스템의 향후 개발, 유지 관리, 업그레이드 및 사용자 경험을 위해 특히 중요합니다.

예외에는 매우 중요한 기능이 있습니다. 예외가 발생한 위치에서 최상위 메인 메소드까지 이를 포착하지 못하면 jvm은 결국 예외 메시지를 표시하게 됩니다. 가장 나쁜 점은 스레드가 중단된다는 것입니다. 이후 코드는 더 이상 실행되지 않고 JVM의 광활한 바다 속으로 조용히 사라집니다. 우리 회사의 이전 프로젝트에서 프런트 엔드 ajax는 컨트롤의 캐치로 인해 null 포인터가 발생했기 때문에 프런트 엔드 페이지가 중단되었습니다. 해결 방법: 컨트롤 레이어는 일반적으로 최상위 레이어이므로 가능한 모든 것을 잡는 것이 가장 좋습니다. 예외가 발생하면 최상위가 아닌 다른 레이어가 계속해서 위쪽으로 던지거나 던질 수 있습니다. 또한 각 Ajax에 대해 시간 제한을 설정하는 것이 가장 좋습니다.

throw 및 throw에 대해 간단히 소개하겠습니다.

throw: 메서드 본문에 예외를 발생시킵니다. 실제 예외 개체는 일반적으로 메서드 이름 뒤에 위치하여 메서드를 나타냅니다. 예외가 발생하면 처리하고 싶지 않거나 처리할 수 없으며 호출자에게 처리하도록 맡깁니다. ClassNotFoundException, NumberFromartException과 같은 런타임 예외(선택 해제)를 발생시키거나 throws 또는 throw+try 또는 throw+throws는 IOExcepion, SocketException 및 상속 예외 클래스와 같은 예외와 같은 확인된 예외를 처리합니다. 차이점은 확인된 예외를 처리해야 한다는 것입니다(try 또는 throw가 계속 발생합니다. 그렇지 않으면 컴파일이 통과되지 않습니다). 반면 런타임 예외는 처리할 필요가 없습니다. 예외가 발생한 후 결과는 다음과 같습니다. jvm이 예외 메시지를 보고하고 스레드가 중단됩니다. throw 및 throws 키워드는 일반적으로 코드에서 사용하지 않는 것이 좋으며 모든 예외를 그 자리에서 해결하는 것이 좋습니다. 사용법만 알면 되는데, 길게 설명할 필요가 없습니다.

Try 조합 규칙: 1, try{}catch(){} 2, try{}catch(){}finally{} 3, try{}finally{}, 1과 2는 여러 개의 catch를 가질 수 있습니다

친구 , 밤 좀 먹어보세요:

1, 조합을 시도하지 마세요

public class CatchExecuteJustOne {

 public void methodOne(){
  System.out.println("into methodOne method");
  int one=1/ ;
cejo.methodOne();

System.out.println("end main method"); //출력 없음, 시도 조합 없음, 오류 스레드 연결이 끊어졌습니다
}
}

출력:


Into methodOne method
스레드 "main" java.lang.ArithmeticException의 예외: / by zero

at priv.lilei.Exception.example_1.CatchExecuteJustOneS.methodOne(CatchExecuteJustOneS.java:6)

at priv.lilei.Exception.example_1.CatchExecuteJustOne.main(CatchExecuteJustOne. .java:19)



2.1, 시도 조합 사례 1이 있습니다

public class CatchExecuteJustOne {

 public void methodOne(){

  System.out.println("into methodOne method");

 try{

int one =1/0;

  }catch(Exception e){
  System.out.println("methodOne try to");
  }
 System.out.println("end methodOne method");
}

 public static void main(String[] args) {
   CatchExecuteJustOne cejo = new CatchExecuteJustOne();
  cejo.methodOne();
  System.out.println("end main method");
  }
}

출력:
methodOne으로 method
methodOne은
methodOne method

end main method

2.2를 시도하고, 조합 케이스 2


public class CatchExecuteJustOne {
public void methodOne(){
 System.out.println("into methodOne method") ;

 int one=1/0;

 System.out.println("end methodOne method"); //스레드가 실행되지 않고 오류가 보고되고 직접 발생합니다.

}


public static void main (String[] args ) {
 try{
  CatchExecuteJustOne cejo = new CatchExecuteJustOne();
  cejo.methodOne();
 }catch(Exception 예외){
  System.out.println("into main method catch"); /will 실행 try to 위 메소드에서 보고된 예외
}
  System.out.println("end main method"); //위 메소드에서 보고된 예외에 대해 try를 실행합니다
}
}

출력:

into methodOne method
into main method catch
end main method

2.3, try Case 조합 3 예외는 최신 catch에 의해 한 번만 catch됩니다. 스위치 케이스의 구문은 if() if else(){} if()else if{}

public class CatchExecuteJustOne {
public void methodOne(){
System.out.println("into methodOne)과 동일합니다. method") ;
try{
int one=1/0;
}catch(ArithmeticException e){
System.out.println("catch 1");
}catch(Exception e) {
System.out.println ("catch 2");//이전 catch를 실행하지 않습니다 1
}
}

public static void main(String[] args) {
CatchExecuteJustOne cejo = new CatchExecuteJustOne();

try {
cejo.methodOne ();
} catch (예외 e) {
System.out.println("man catch");//이미 실행된 catch를 실행하지 않습니다. 1
}

System.out.println("end main method") ;
}
}

출력:

into methodOne method
catch 1
end main method

2.4 try 조합 사례 4, try{}finally{} 조합이 있으며, 마침내 반환에 실패하면 스레드 연결이 끊어집니다. 값이 있지만 finally에 반환 값이 있는 경우 스레드의 연결이 끊어지지 않지만 후속 코드는 실행되지 않습니다. 이 조합은 드물게 사용하는 것이 좋습니다.

//반환값 없음

public class CatchExecuteJustOne {
  public void methodOne(){ //반환값 없음
  System.out.println("into methodOne method");
 try{
  int one=1 /0;
 }finally{
  System.out.println("into methodOne finally");
  }
   System.out.println("end methodOne method") // 다음과 같은 경우 스레드를 실행하지 않고 직접 버립니다. 오류가 보고되었습니다
}

public static void main(String[] args) {
  CatchExecuteJustOne cejo = new CatchExecuteJustOne();
 cejo.methodOne();
 System.out.println("end main method");/ /No 실행 스레드가 오류를 보고하고 연결이 끊어져 반환 값 없이 직접
}
}

출력:

into methodOne method
Exception in thread "main" into methodOne finally
java.lang.ArithmeticException: / by zero
at priv .lilei.Exception.example_1.CatchExecuteJustOne.methodOne(CatchExecuteJustOne.java:14)
at priv.lilei.Exception.example_1.CatchExecuteJustOne.main(CatchExecuteJustOne.java:23)

반환 값:

public class CatchExecuteJustOne {
public String methodOne(){
System.out.println("into methodOne method");
try{
System.out.println("1");
int one=1/0;
System.out.println("2");//실행 스레드는 오류를 보고하지 않고 중단되어 직접 발생합니다
}finally{
System.out.println("into methodOne finally");//출력됩니다.
return "1";
}
}

public static void main(String[] args) {
CatchExecuteJustOne cejo = new CatchExecuteJustOne();
cejo.methodOne();
System.out.println("end main 메소드 ");//실행됩니다. 위의 시도가 있고 메서드에 반환 값이 있으므로
}
}

반환 값의 출력이 있습니다.

into methodOne method
1
into methodOne finally
end main method

2.5, finally와의 조합은 항상 실행됩니다. 반환 값이 있으면 system.exit(0)과 같은 특별히 폭력적인 동작이 있거나 중단되지 않는 한 반환 전에 실행됩니다. , 또는 메모리 오버플로 등의 오류가 있습니다.

return 조합

2.5.1 다음 두 경우에는 catch에서 다시 변수에 값을 할당하는 것과 마지막으로 예외가 없을 때와 예외가 있을 때 차이가 있습니다. 예외가 없으면 할당이 다시 실패하지만, 예외가 있으면 할당이 다시 성공합니다.

1 예외 없음

public class CatchExecuteJustOne {
public String methodOne(){
String a="";
System.out.println("into methodOne method");
try{
a= "a";
return a;
}catch(ArithmeticException e){
System.out.println("catch 1");
}마지막으로 {
System.out.println(1);
a="a2 "; //오류가 보고되지 않으면 값이 a;
System.out.println(2);
}
System.out.println(3);에 할당되지 않습니다. //위 반환 메서드는 실행되지 않으며 a 메소드가 반환되었습니다
return a;
}

public static void main(String[] args) {
CatchExecuteJustOne cejo = new CatchExecuteJustOne();
System.out.println(cejo.methodOne());
}
}

None 반환 시도 비정상적인 상황 출력:

into methodOne method
1
2
a

2 비정상적인 상황이 있습니다

public class CatchExecuteJustOne {
public String methodOne(){
String a="";
System.out.println("into methodOne method");
try{
a="a";
int i=1/0 ;
return a;
}catch(ArithmeticException e){
System.out.println("catch 1");
}마지막으로 {
System.out.println(1);
a="a2"; 예외는 변수 a에 재할당됩니다.
System.out.println(2);
}
System.out.println(3); //예외는 위의 첫 번째 반환 a에서가 아니라 출력 및 캡처됩니다. 아래 반환 return
return a;
}

public static void main(String[] args) {
CatchExecuteJustOne cejo = new CatchExecuteJustOne();
System.out.println(cejo.methodOne());
}
}

try 반환에 비정상적인 출력이 있습니다.

into methodOne method
catch 1
1
2
3
a2

위 내용은 Java 기본 값: 예외 처리 키워드...의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.