Why is it necessary to be able to throw an exception in an attempt to write a catch?

I played with some programs with exceptions and came across with the fact that I was surprised that I had never met before.

import java.io.*;

class ExceptionTest
{
  public static void main(String[] args)
  {
    try
    {
      System.out.println("hello");
    }
    catch(IOException ioe)
    {
      System.err.println("ioexception was thrown!!");
    }
  }
}

a compiler error occurs:

ExceptionTest.java:10: exception java.io.IOException is never thrown in body of
corresponding try statement
catch(IOException ioe)
^
1 error

My question is: why is this so?

Why is the compiler worried about a piece of code, it is sure that it will never reach. It may just be a warning, not a complete mistake. In the end, we might want to keep the catch block as a backup for some future changes that we could make, or maybe the programmer just forgot to delete it after some changes.

I know that I know that this saves us from unnecessary keystrokes, etc. But this should not interfere with the compiler to cause an error. Or is there some other reason for this?

, catch IOException , catch ... ? Thnx !

+3
4

Java , . , :

public class EarlyReturn {
    public void foo() {

        return;

        System.out.println("Hi");
    }
}

..., . , , , , , , , , .

, Exception, IOException, , , , (, , ).

catch IOException , catch Exception ... ?

IOException - , ( ). , (RuntimeException ) (Error ). - , ( 11.1.1 JLS), — — . , , Exception . 11.2.3 JLS:

, catch E1, , try, catch, , E1, E1 Exception Exception.

11, , . , Java, , , .

+8

, : " ?".

:

try {
     System.out.println("Guards!! Someone is stealing the crown jewels!");
} catch(IOException ioe) {
     CallTheArmy();
}

, , , (- IOException), . , println IOException.

, .

+3

Java . (JLS 14.21) try ... catch, . , IOException, try ... catch. , , , .

EDITED, : " catch IOException , catch ... ? Thnx !"

catch . (, , RuntimeException s) , , , RuntimeException.

+2

IOException RuntimeException, , try ... catch - , throws IOException.

: .:) , : , return , , .

thagorn : . RuntimeException - " , Java". (Javadocs). , IOException , RuntimeException .

0