Error handling with if statement - java

This is to validate my GUI input and make sure the user can not enter values out of range
I'm trying to handle this exception with if statement but I'm still printing the red error message. I just want the "Value out of range" message to be printed. I don't want those red exceptions error in my console. Please help or advise. Any other way to handle this can is fine with me.
if (totalTimeToTakeOff <= 0 || totalTimeToLand <= 0 || arrivalRate < 0
|| arrivalRate > 1 || departureRate < 0 || departureRate > 1
|| remaingFuel <= 0 || numOfRunways <= 0 || sIMULATION_TIME < 0) {
throw new IllegalArgumentException("Values out of range");
}

Well what you are doing here is creating a new IllegalArgumentException object, and then this method throws this exception. When you throw an exception, the part of your code that calls this method has to handle that exception OR those 'red lines' (the stack trace, basically) are printed. So, for a simple example, say that you have the method divide()
public double divide(double a, double b){
if(b==0){
throw new IllegalArgumentException("Divisor cannot be 0");
}
return a/b;
}
Now, when some other part of your code calls this method, you can choose to handle the IllegalArgumentException that is thrown by this method.
try{
double c = divide(a,b);
}catch(IllegalArgumentException e){
//put whatever code you want here
}
If you don't catch the exception, then your code breaks and the stack trace (the red text) is printed out. So in other words, your code is functioning as intended; that section of code throws an IllegalArgumentException under some circumstance, and the code that calls that method does not catch the exception and handle it (for example by printing out the message about the exception).
Also, just a minor note- an error in java is different from an exception. An error signifies a process from which the program cannot recover, and an error cannot be caught. Exceptions (all classes that subclass the Exception class) can be caught. An exception can either be checked or unchecked - checked exceptions MUST be caught via a catch statement, whereas unchecked exceptions don't. An example of a checked exception is the IOException, whereas an example of an unchecked exception is the IllegalArgumentException you have displayed here.
One more thing- exceptions are meant to signify an abnormality in your code. If this IllegalArgumentException was thrown from say, a class constructor or a method that can be used for many general purposes, then it makes sense to throw it. However, if that method exists solely for the purpose of checking whether input is valid, then have it return a boolean value (true or false) rather than throwing an exception.
One other reason to this is because exception handling tends to be rather slow in comparison to simply returning a true or a false.

You need to understand this please look into it.
Basic understanding is
try {
//Something that can throw an exception.
} catch (Exception e) {
// To do whatever when the exception is caught.
}
There is also an finally block which will always be execute even if there is an error. it is used like this
try {
//Something that can throw an exception.
} catch (Exception e) {
// To do whatever when the exception is caught & the returned.
} finally {
// This will always execute if there is an exception or no exception.
}
InputMismatchException - if the next token does not match the Integer regular expression, or is out of range
NoSuchElementException - if input is exhausted
IllegalStateException - if this scanner is closed
So you would need to catch exceptions like
try {
rows=scan.nextInt();
} catch (InputMismatchException e) {
// When the InputMismatchException is caught.
System.out.println("The next token does not match the Integer regular expression, or is out of range");
} catch (NoSuchElementException e) {
// When the NoSuchElementException is caught.
System.out.println("Input is exhausted");
} catch (IllegalStateException e) {
// When the IllegalStateException is caught.
System.out.println("Scanner is close");
}

You could just print to the console and exit Java (instead of throwing an exception), as that is what an Exception does in essence.
System.out.println("Values out of range");
System.exit(0);
Alternatively, catch the exception when calling the method
try{
if(checkValues())
...
}catch(Exception e){
System.out.println("Values out of range");
}

you could check the values without throwing an exception
if (!checkValues())
System.out.println("Values out of range");

Related

How to handle exceptions that you didn't expect even thought it is declared on the documentation?

When there are methods that throw exceptions and you know these exceptions will not be thrown, what should you do?
Many times I see people just logging the exception, but I wonder if there is a build in exception in java that means something like: "This exception should not have been thrown".
For example, imagine I have a code that calls StaticClass.method(someObject) and this method throws a SpecificException when someObject is not valid. What should you do in the catch block?
try {
StaticClass.method(someobject);
} catch (SpecificException e) {
// what should I do here?
}
If when calling the method you know for sure that it will not throw an exception because of previous checks you should throw a RuntimeException wrapping the SpecificException.
try {
StaticClass.method(someobject);
} catch (SpecificException e) {
//This is unexpected and should never happen.
throw new RuntimeException("Error occured", e);
}
Some methods already throw a RuntimeException when they fail to perform their purpose.
//Here we know for sure that parseInt(..) will not throw an exception so it
//is safe to not catch the RuntimeException.
String s = "1";
int i = Integer.parseInt(s);
//Here instead parseInt(..) will throw a IllegalArgumentException which is a
//RuntimeException because h is not a number. This is something that should
//be fixed in code.
s = "h";
i = Integer.parseInt(s);
RuntimeExceptions don't require a try/catch block and the compiler will not be mad at you for not catch them. Usually they are thrown where something in your app code is wrong and should be fixed. Anyway there are cases where catching a RuntimeException is useful.

Try Catch block works but test assertThrows fail (Junit 5)

I am trying to follow this tutorial JUnit 5: How to assert an exception is thrown?
I use Java 10, IntelliJ 2018 and Junit 5.
I make a calculator app that adds 2 fractions. It checks whether the input has 0 in the denominator.
When I run the test The exception Message get printed out "Undefined Math Expression" but my IDE says "Expected java.lang.Throwable to be thrown, but nothing was thrown." I think there is some problem with the scope of my code? I'm a newbie, please be kind. I provided the code and the test below:
public class Calculator {
public static int[] calculate (int firstNumerator, int firstDenominator, int secondNumerator, int secondDenominator) {
String exceptionMessage = "Undefined Math Expression";
int resultNumerator;
int resultDenominator;
int[] result = new int[2];
resultNumerator = (firstNumerator * secondDenominator) +
(secondNumerator * firstDenominator);
resultDenominator = firstDenominator * secondDenominator;
try {
if (resultDenominator == 0) {
throw (new Throwable(exceptionMessage));
} else {
result[0] = resultNumerator;
result[1] = resultDenominator;
}
} catch (Throwable e) {
System.out.println(e.getMessage());
}
return result;
}
}
The test:
class CalculatorTest {
#Test
void denominatorContainsZero() {
assertThrows(Throwable.class, () -> {
Calculator.calculate(0,0,0,0);
});
}
}
The misunderstanding here appears to be in what JUnit can actually see.
JUnit isn't magical: it's just plain old Java. It can't see inside your methods to see what they are doing. All it can see is what any other code can see when it executes a method: the return value and uncaught exceptions (as well as any side effects of the method, if they are visible to the calling code).
Your method here doesn't throw an exception from the perspective of a caller: internally, it throws the exception, but it catches and handles it.
If you want JUnit to test that an exception is thrown, you need to not catch that exception.
It is never (*) the right thing to do to throw an exception and then catch and handle it yourself. What's the point? You can simply do the thing you do to handle it, without throwing the exception. Exceptions are expensive to throw, because of the need to capture the entire stack trace.
Throwable is never (*) the right exception to throw. It's the exception "equivalent" of returning Object: it conveys no type information about the exception to the caller, who then either has to do a lot of work to try to handle it; or, more realistically, should just propagate it themselves. IllegalArgumentException is the right exception to throw here, if you actually needed to throw (and not catch) an exception.
Throwable is rarely the right thing to catch. Throwable is a supertype of both Exception and Error, so you might unintentionally catch an Error, like OutOfMemoryError, which shouldn't be caught because there is nothing reasonable to do except crash your program. Catch the most specific type you can; which also means that you should throw the most specific type you can (or, at least, a type appropriate to the abstraction).
(*) This is "never" as in "ok, there are a limited number of circumstances where it may be appropriate". But unless you understand what these are, don't.
The Throwable is catched by try catch block, so Junit can not access it. Try remove the try catch block.
You are not actually throwing exception, you are catching it. For this to work, you should remove try catch block.

Can a checked exception be used to throw an unchecked exception?

I am running the following code:
import java.io.FileNotFoundException;
import java.io.IOException;
class Basic1 {
int c;
void calculation(int a, int b) throws Exception {
c = a / b;
}
}
class Basic extends Basic1 {
void calculation(int a, int b) throws IOException {
c = a / b;
RuntimeException ae = new ArithmeticException();
throw ae;
}
public static void main(String[] args) {
int a = 10;
int b = 0;
int c;
Basic ba = new Basic();
try {
ba.calculation(a, b);
} catch (IOException e) {
System.out.println("Zero can't be there in the denominator. : IoException");
} catch (ArithmeticException e) {
System.out.println("Zero can't be there in the denominator. : Arthimetic Exception");
} catch (Exception e) {
System.out.println("Zero can't be there in the denominator. : Exception");
}
}
}
The program is compiling successfully and outputting "Zero can't be there in the denominator. : Arthimetic Exception" (output is as expected).
My question is how is the program able to compile successfully? Why am I not getting an error when I throw an IOException while inside calculation() I am creating a RuntimeException object?
My second question is given that the program enters the catch (ArithmeticException e) clause, is the compiler deciding at run time which catch will execute? Do I understand correctly?
For your first question, methods using the throws E (where E is some arbitrary checked exception) construct don't have to throw anything. All it means is that anyone calling your method has to be able to handle E, which allows your method to throw E without handling it. This would otherwise be a compilation error. Usually, the documentation of your method specifies when E is thrown. In the words of the JLS:
Essentially, for each checked exception that can result from execution of the body of a method or constructor, a compile-time error occurs unless its exception type or a supertype of its exception type is mentioned in a throws clause in the declaration of the method or constructor.
This doesn't say you must throw the given checked exception within the method body. Note that you can use throws with unchecked exceptions, but this has no effect on the program, as unchecked exceptions may be thrown anywhere without being handled. That's the point of them.
In your code, you throw a RuntimeException. Any class extending RuntimeException (including itself) is unchecked by definition. ArithmeticException is one of these, so you may assign it to a variable of type RuntimeException and then throw it without specifying it in the throws clause.
For your second question, I'll assume that the compiler doesn't optimise away the various catch clauses. In that case, no, the catch which is executed is not determined at compile time. When any exception is thrown in your program, it propagates up the stack until it is caught. If it isn't, it halts execution and the stack trace is printed to System.err. Since an ArithmeticException is thrown, the first catch clause does not match but the second one does, so is executed. The third one (catch (Exception e)) would match, but order matters with catch clauses and only one is executed, so that clause is not executed here.
However, in this case, it is not inconceivable that the compiler optimises away your catch clauses and directs the program straight to the code in the catch (ArithmeticException e) clause, as your method will always throw ArithmeticException. It must be considered, however, that any line of code may throw some obscure error like OutOfMemoryError; the compiler must allow for such edge cases when optimising.

If a socket accept causes a exception, how can I find out the reason?

I'm creating a function that will do a socket accept and return 3 vales
0=really bad error happen exit thread
1=ok talk to the connection
=something happen, do another accept (time out).
I see the IOException has a GetCause meths that returns a throwable object.
this throwable object has a get cause method that returns a throwable, which has a getcuase method returning a throwable, seems like this would go on forever, keep getting another throwable object.
How can I get the reason the exception ant off?????
I could use get reason and a bunch of string compares, but this does not seem to reliable.
Ted
int GetClient()
{
try {
server.setSoTimeout(5*1);
connection=server.accept();
}
catch(IOException ec)
{
System.out.println(Thread.currentThread()+":"+ec.getMessage());
return 2; // for time out or something where we can try again
// return a zero saying we must stop erra o bad
}
return 1;
}
accept()
throws a variety of exceptions.
SocketTimeoutException extends IOException but you can 'catch' it before catching the general IOException. This will allow you to return the value suggesting you can try again.
Does this cover your 3 cases, Ok, IOException and Timeout?
If you're only interested in timeout exceptions then catch those exceptions separately. Most IO methods can potentially throw an IOException, but there are many different subclasses of IOException (which themselves have further subclasses) that you can catch and deal with separately.
eg.
try {
conn = server.accept();
} catch (SocketTimeoutException e) {
return 2;
} catch (IOException e) {
// socket exception will not be recaught
// even if return statement wasn't used
return 0;
}
return 1;
The getCause method is provided as when exceptions are created they can be created with string message, but also the exception that may have caused this exception to be thrown. Thus allowing catchers of the exception to see the full detail of what caused the exception.
eg.
public double addNumbers(String a, String b) {
try {
double i = Double.parseDouble(a);
double j = Double.parseDouble(b);
return i + j;
} catch (NullPointerException cause) {
throw new IllegalArgumentException(
"Arguments aren't allowed to be null", cause);
} catch (NumberFormatException cause) {
throw new IllegalArgumentException(
"One or more arguments weren't numbers", cause);
}
}
The above case is a little obtuse, but it demonstrates the principal that some exception may be caught (that maybe it might try to be recovered from) and then a new exception thrown with the original exception as the cause. Having a getCause method allows the caller to immediately see that the IllegalArgumentException was originally thrown in the addNumbers method (and that this is where the problem in the user code base is). However, by looking at the cause they will be able to see a more detailed message about by the argument was illegal (NumberFormatException includes the string that was trying to be parsed).

Learning Try-Catch

I'm a Java beginner so please bear with me
static int load = 100;
static int greet;
public void loadDeduct(int cLoad, int c){
int balance;
balance = cLoad - 7;
System.out.println("Your balance: " + balance);
}
public void loadDeduct(int tLoad){
int balance;
balance = tLoad - 1;
System.out.println("Your balance is: " + balance);
}
public static void main (String [] args){
int choice;
Scanner scan = new Scanner(System.in);
System.out.println("I'm a cellphone, what do you want to do?");
System.out.println("Press 1 to send SMS / Press 2 to Call");
choice = scan.nextInt();
CellphoneLoad N95 = new CellphoneLoad();
if (choice == 1){
N95.loadDeduct(load);
}else if (choice == 2){
N95.loadDeduct(load, greet);
}else{
System.out.println("Invalid Option!!!");
}
How do I implement the exception handling with this program?
I'm not quite sure how to use the catch block as we weren't taught yet about the whole exceptions thing. It was just an exercise we were asked to do. I want to replace the if else statements with a try-catch blocks... is that possible?
One important principle to consider with exceptions in Java is that there are two types:
1. Runtime
2. Typed/explicit (for lack of a better word)
Runtime exceptions should be thrown when there is a programming error and generally they should not be caught unless you are catching at the top level to report an error.
Typed/Explicit exceptions are decorated on method calls and should be there so the caller can take some action on them.
In the case of the code above, there isn't really a place that feels like it should use exception handling.
And as Patrick pointed out, you don't generally want to use exceptions for flow control.
It is not ideal to use Exceptions for flow control. From your code it is not clear what Exceptions might be thrown. Maybe you can elaborate a bit more.
The Scanner.nextInt() method can throw a few exceptions. The linked page of the API Specifications lists out the three exceptions which can be thrown.
For example, if a non-integer value is entered, such as "one" instead of 1, an InputMismatchException can be thrown.
In general, a try-catch is used to catch exceptions, as illustrated in the following code:
try
{
Integer.parseInt("one"); // Statement that can cause an exception.
}
catch (NumberFormatException e) // Specify which exception to catch.
{
// Code to handle the NumberFormatException.
}
More information about exceptions can be found in Lessons: Exceptions of The Java Tutorials. In particular, the Catching and Handling Exceptions section may be useful.
Adding exceptions in this piece of code does not add much value.
What I can think of is something like this:
public static void main (String [] args){
.....
try{
handleUserChoice(choice);//new method
}
catch(InvalidChoiceException e){
System.out.println("Invalid Option!!!");
}
}
The only part of your code that might possibly throw an exception is the call to:
scan.nextInt();
According to the JavaDocs, this can throw the following possible exceptions:
InputMismatchException (if the next
token does not match the Integer
regular expression, or is out of
range)
NoSuchElementException (if
input is exhausted)
IllegalStateException (if this
scanner is closed)
So if you wanted your code to account for the possibilities of these exceptions being thrown, you should re-write it like so:
try {
choice = scan.nextInt();
}
catch (InputMismatchException e) {
System.out.println(e.getMessage());
}
catch (NoSuchElementException e) {
System.out.println(e.getMessage());
}
catch (IllegalStateException e) {
System.out.println(e.getMessage());
}
Generally, you want your "catch" blocks to start out specific or very likely to happen to less likely / more general in nature.
You can additionally "throw" the exceptions so that whatever method the exception occurs in doesn't handle it-- the method which called that exception-causing method would have to handle it (or throw it again, etc, until it gets to the Java runtime).
In the event it's the "if" statement you wish to replace, I'd recommend the "switch" statement:
switch (choice) {
case 1: N95.loadDeduct(load);
break;
case 2: N95.loadDeduct(load, greet);
break;
default: System.out.println("Invalid Option!!!");
}
I don't see any reason to use exceptions instead of the if-else block. you could try using a switch statement, it'd look better.
you should use exceptions to handle errors that might occur inside the methods loadDeduct. then you would surround the lines calling N95.loadDeduct with a try-catch block, to write what would happen if loadDeduct went wrong.
It's really pretty simple. First identify where you want an exceptioon. There can be exceptinos thrown by library code or you can throw your own. Then use a try .. catch to handle it. Here's a simple "hello, world" ish example:
public class TryTry {
public void doIt() throws Exception {
System.err.println("In the doIt method.");
throw new Exception("Hello there!");
}
public static void main(String[] argv){
TryTry t = new TryTry();
// here we'll catch it.
try {
System.err.println("About to call doIt().");
t.doIt();
} catch (Exception e) { // e now has your exception object
System.err.println("In the exception handler.");
System.err.println("Exception says: "+ e);
}
}
}
The effect of throw is to construct that exception object and send it up the stack until it's caught. To catch it, you surround the code that might throw it with tr { ... }, and handle the exception with catch.
Here's the results:
javac TryTry.java && java TryTry
About to call doIt().
In the doIt method.
In the exception handler.
Exception says: java.lang.Exception: Hello there!

Categories