throw

2 0 0
                                    

You can't catch an exception if you haven't thrown something. That was the reason I was required to add throws in the readSomething() method.

throw - This is used to throw an exception and it requries an object of Exception.

throws  - This works like the throw above but this is used after the method parameters as an extension when your method get an exception. Since this works like an extension, you can separate different exception with a comma. 

void readFile(String name) throws IOException, IndexOutOfBoundsException{ // block }

But the difference is when you use throws, the program will stop right away in there and won't process the others while throw, you can use a catch and let the process continue.

=================

class PracticeThrow{

    public static void main(String[] args){

          PracticeThrow.dividingNumbersRev(6, 2);

          PracticeThrow.dividingNumbers(6, 0);

    }

    private static void dividingNumbers(int x, int y){

          try{

                 if(y == 0){

                       throw new AritmeticException();

                   }else {

                        System.out.println("answer: " + (x/y));

                    }

           }catch(ArithmeticException e){

                System.out.println("Error: " + e.fillInStrackTrace());

           }

     }

     private static void dividingNumbersRev(int x, int y) throws ArithmeticException{

          System.out.println("answerRev: " + (x/y));

      }

}

================

Result:

answerRev: 3

Erro: java.lang.ArithmeticException


Note: Stack trace is a list of information about the classes and methods called before the error occurs. Is possible for an exception to have another exception that it chains. You can use the Throwable class to check for the cause. There are some advantages when you used exceptions but I don't want to go through that.


Java ProgrammingWhere stories live. Discover now