-6

Within the first catch block why we can't throw an Exception object? Here RuntimeException is working fine.

public class CirEx {
    public Circle getCircle(int id) {
        Connection conn = null;
        try {
            Class.forName("");
            conn = DriverManager.getConnection("");
            PreparedStatement pstmt = conn.prepareStatement("");

            Circle circle = new Circle(1, "");
            return circle;
        } catch (Exception e) {
            throw new RuntimeException(e);
            // why we cann't do that.
            // throw new Exception(e);
        } finally {
            try {
                conn.close();
            } catch (SQLException e) {
                System.out.println(e);
            }
        }
    }
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Abhi
  • 13
  • 3

2 Answers2

1

We can throw Exception, provided we declare the method to throw the same Exception (throws Exception clause) or handle it (using try catch block) .

Exception is a checked exception and these have to be handled

but

RuntimeException works because its unchecked Exception and for this we need not have a throws clause or handle it

See Checked vs Unchecked Exception

Community
  • 1
  • 1
sanbhat
  • 17,522
  • 6
  • 48
  • 64
-2

Because in that case you will have to declare your method that it throws Exception.

 public Circle getCircle(int id) throws Exception{
Connection conn = null;
try {
    Class.forName("");
    conn = DriverManager.getConnection("");
    PreparedStatement pstmt = conn.prepareStatement("");

    Circle circle = new Circle(1, "");
    return circle;
} catch (Exception e) {
    throw new RuntimeException(e);
    // why we cann't do that.
    // throw new Exception(e);
}

finally {
    try {
        conn.close();
    } catch (SQLException e) {
        System.out.println(e);
    }
}

}

Note:RuntimeException and its subclass are special type exception which don't need to be catched explicitely

mawia
  • 9,169
  • 14
  • 48
  • 57