programing

예외 처리 : throw, throws 및 Throwable

randomtip 2021. 1. 14. 08:13
반응형

예외 처리 : throw, throws 및 Throwable


당신의 어떤 차이점이 사이에 무엇인지 설명 할 수 throw, throws그리고 Throwable언제 어떤 사용하는 방법?


  • throws: 메서드를 작성할 때 문제의 메서드가 지정된 (확인 ​​된) 예외를 throw 함을 선언하는 데 사용됩니다.

    확인 된 예외와 달리 런타임 예외 (NullPointerExceptions 등)는 메서드 선언없이 throw 될 수 있습니다 throws NullPointerException.

  • throw: 실제로 예외를 발생시키는 명령입니다. (또는 더 구체적으로 Throwable ).

    throw 키워드 뒤에는 Throwable(일반적으로 예외) 참조가옵니다 .

예:

여기에 이미지 설명 입력


  • Throwable: 자신 만의 커스텀 스로 블을 만들기 위해 확장해야하는 클래스입니다.

예:

여기에 이미지 설명 입력



  • throw: true 여야하는 t곳에 객체를 던지는 문 t instanceof java.lang.Throwable.
  • throws: 해당 메소드에 throw의해 확인 된 예외 n 을 지정하는 메소드 서명 토큰 .
  • java.lang.Throwable: 던질 수있는 (그리고 잡힐 수있는) 모든 객체의 부모 유형.

예외 사용에 대한 자습서는 여기를 참조하십시오.


이것은 정말 이해하기 쉽습니다.

java.lang.Throwable의 :

Throwable클래스는 Java 언어의 모든 에러와 예외의 슈퍼 클래스입니다. 이 클래스 (또는 하위 클래스 중 하나)의 인스턴스 인 객체 만 Java Virtual Machine에서 처리되거나 Java throw문에서 처리 될 수 있습니다 . 마찬가지로이 클래스 또는 하위 클래스 중 하나만 catch절의 인수 유형이 될 수 있습니다 .

throws 키워드 메소드 선언에 사용되며,이 메소드에서 예상 할 수있는 예외 [Throwable 클래스]의 종류를 지정합니다.

던지는 키워드 는 Throwable 클래스의 인스턴스 인 객체를 던지는 데 사용됩니다.


몇 가지 예를 보지 않도록 :

우리는 스스로 예외 클래스를 만듭니다.

public class MyException super Exception {

}

우리는 우리의 예외 클래스로부터 객체를 생성하는 방법 만들 발생 키워드를 사용하여 던져 .

private  void throwMeAException() throws MyException //We inform that this method throws an exception of MyException class
{
  Exception e = new MyException (); //We create an exception 

  if(true) {
    throw e; //We throw an exception 
  } 
}

method를 사용할 때는 throwMeAException()무언가를 던지는 정보가 있기 때문에 특정 방식으로 처리해야합니다.이 경우 세 가지 옵션이 있습니다.

첫 번째 옵션은 블록 try 및 catch를 사용하여 예외를 처리하는 것입니다.

private void catchException() {

   try {
     throwMeAException();
   }
   catch(MyException e) {
     // Here we can serve only those exception that are instance of MyException
   }
}

두 번째 옵션은 예외를 전달하는 것입니다.

   private void passException() throws MyException {

       throwMeAException(); // we call the method but as we throws same exception we don't need try catch block.

   }

세 번째 옵션은 예외를 포착하고 다시 던지는 것입니다.

private void catchException() throws Exception  {

   try {
     throwMeAException();
   }
   catch(Exception e) {
      throw e;
   }
}

Resuming, when You need to stop some action you can throw the Exception that will go back till is not server by some try-catch block. Wherever You use method that throws an exception You should handle it by try-catch block or add the declarations to your methods.

The exception of this rule are java.lang.RuntimeException those don't have to be declared. This is another story as the aspect of exception usage.


throw - It is used to throw an Exception.The throw statement requires a single argument : a throwable class object

throws - This is used to specifies that the method can throw exception

Throwable - This is the superclass of all errors and exceptions in the Java language. you can throw only objects that derive from the Throwable class. throwable contains a snapshot of the execution stack of its thread at the time it was created


Throw is used for throwing exception, throws (if I guessed correctly) is used to indicate that method can throw particular exception, and the Throwable class is the superclass of all errors and exceptions in the Java

How to Throw Exceptions


Throw :

is used to actually throw the exception, whereas throws is declarative for the method. They are not interchangeable.

throw new MyException("Exception!);

Throws:

This is to be used when you are not using the try catch statement in your code but you know that this particular class is capable of throwing so and so exception(only checked exceptions). In this you do not use try catch block but write using the throw clause at appropriate point in your code and the exception is thrown to the caller of the method and is handled by it. Also the throws keyword is used when the function may throw a checked exception.

public void myMethod(int param) throws MyException 

There are 2 main types of Exceptions:
Runtime Exceptions(unchecked): eg. NullPointerException, ClassCastException,..
Checked Exceptions: eg. FileNotFoundException, CloneNotSupportedException, ..

Runtime Exceptions are exceptions that occur at runtime and the developer should not try to catch it or stop it. You only write code to avoid them or issue a command throw, when the error criteria is met. We use throw inside the method body.

public Rational(int num, int denom){
if(denom <= 0) {
  throw new IllegalArgumentException("Denominator must be positive");
}
this.num=num;
this.denom=denom;
}

However for Checked Exceptions, the JVM expects you to handle it and will give compiler error if not handled so you declare that it throws that type of exception as seen below in the clone() method.

Class Employee{
public Employee clone() throws CloneNotSupportedException{
    Employee copy = (Employee)super.clone();
    copy.hireDate = (Date)hireDate.clone();
    return copy;
}
}

Same answer as above but with copy-paste pleasure:

public class GsonBuilderHelper {
    // THROWS: method throws the specified (checked) exception
    public static Object registerAndRun(String json) throws Exception {

        // registering of the NaturalDeserializer
        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.registerTypeAdapter(Object.class, new NaturalDeserializer());
        Gson gson = gsonBuilder.create();

        Object natural = null;
        try {
            // calling the NaturalDeserializer
            natural = gson.fromJson(json, Object.class);
        } catch (Exception e) {
            // json formatting exception mainly
            Log.d("GsonBuilderHelper", "registerAndRun(json) error: " + e.toString());
            throw new Exception(e);  // <---- THROW: instance of class Throwable. 
        }
        return natural;
    }
}

참조 URL : https://stackoverflow.com/questions/3940213/exception-handling-throw-throws-and-throwable

반응형