-6

I came from .net world.

I have some question about exceptions in java.

What is deference between two attitude of throwing exceptions:

public void f() throws Exception {
     //some logic
}

and this:

public void f() {
    //some logic
    throw new Exception();
}   

When should I use first attitude and the second attitude?

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
Michael
  • 13,950
  • 57
  • 145
  • 288
  • Do it in the second way if you don't mind it not being valid Java. – Andy Turner Jul 14 '17 at 22:41
  • The second is invalid. You want `throw [new Exception()]`. – cs95 Jul 14 '17 at 22:42
  • @cᴏʟᴅsᴘᴇᴇᴅ and `throws Exception` on the method signature, because you can't have an unhandled checked exception. – Andy Turner Jul 14 '17 at 22:42
  • @AndyTurner Yep, that too. – cs95 Jul 14 '17 at 22:44
  • 2
    @Michael I think you would be well-served by reading [the Oracle tutorial on exceptions](https://docs.oracle.com/javase/tutorial/essential/exceptions/). Your question suggests there are some important concepts that you've not understood (like `throw` vs `throws`; checked vs unchecked exceptions). – Andy Turner Jul 14 '17 at 22:44

2 Answers2

1

In Java, you need to specify how your method behaves. This includes exceptions that can possibly be thrown. To declare, that you method can that an exception, the throws keyword is used (as in your first Example).

Note that only Exceptions that derive from the Exception class must be depicted here (there are also RuntimeExceptions and other Throwables that do not need to be depicted. More here).

To throw an Exception you need the keyword throw followed by the instance of any Exception (to be precise, you can throw any Throwable).

A valid method would be:

public void foo() throws Exception {
    throw new Exception();
}
tuberains
  • 191
  • 9
1

There is a difference in using these two. Assuming the second method is without s. The first approach, throws, used in the method signature, denoting which Exception can possible be thrown by this method. You can declare multiple exception classes. For checked Exception, the caller can either handle this exception by catching it or can rethrow it by declaring another throws in method declaration.

public void f()throws IOException, SQLException { //some logic }

The second approach, using throw without s is used in any part of code followed by an instance whenever you need to throw a specific exception to the caller.

public void f(){  
  //some logic
 throw new ArithmeticException("sorry");  
}

You can get more information throw and throws in Java

Abereham
  • 141
  • 3
  • 9