Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if statement for throwing Exception?

Tags:

Hi I wanted to ask because I'm not sure if is it propriete using of Exception:

public int Method(int a, int b) {    if(a<b) throw new ArgumentException("the first argument cannot be less than the second");    //do stuff...  } 

can I throw Exception after if statement? or should I always use try - catch when it goes with the exceptions?

like image 471
TrN Avatar asked May 31 '11 08:05

TrN


People also ask

Can you throw an exception in an if statement?

should I use the throw outside or inside an "if" statement? You definitely should throw exception inside the if condition check.

Can we throw exception in if block?

8 Answers. Show activity on this post. It makes no sense to throw an exception in a try block and immediately catch it, unless the catch block throws a different exception. You only need the try-catch block if your business logic (executed when the condition is true ) may throw exceptions.

How do you handle an exception in an if statement in Java?

You could do this by looking into the Javadoc or use your favorite IDE. If you catch Exception as the Exception class, it catches every Exception that is subclass of it. To achieve different Exceptions thrown in your code the methods should at least throw different exceptions. In your example with file.

How do you know if a method throws an exception?

The calculate method should check for an exception and if there is no exception, return the calculated value to the main function i.e. v1+v2 or v1-v2; Else if an exception exists then it should print the error statement and the value that is returned from the calculate method to the main method should be 0.0(Not ...


1 Answers

That is perfectly valid. That is exactly what exceptions are used for, to check for "Exceptions" in your logic, things that weren't suppose to be.

The idea behind catching an exception is that when you pass data somewhere and process it, you might not always know if the result will be valid, that is when you want to catch.

Regarding your method, you don't want to catch inside Method but infact when you call it, here's an example:

try {     var a = 10;     var b = 100;     var result = Method(a, b); } catch(ArgumentException ex)  {     // Report this back to the user interface in a nice way  } 

In the above case, a is less than b so you can except to get an exception here, and you can handle it accordingly.

like image 120
Filip Ekberg Avatar answered Oct 21 '22 11:10

Filip Ekberg