Learning Try-Catch - java

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!

Related

Is it okay to call the the method a try catch statement is in with the finally block

I made a switch case statement menu with one of the options being System.exit(0);. This is all surrounded by a try, finally that calls the method all of this is in. Would you guys not recommend this style of loop or am I all good?
public void Run() {
Scanner myObj = new Scanner(System.in);
int menuInput;
try {
System.out.println(" 1) call something\n"
+"2) quit");
menuInput = myObj.nextInt();
myObj.nextLine();
switch(menuInput) {
case 1:
something();
break;
case 2:
System.exit(0);
break;
}
}catch (Exeption e ){
System.out.println("Something went wrong.");
}finally{
Run();
}
}
No.
What you have here is an infinite recursion. Eventually you'd overflow the stack.
Use an actual loop instead:
while (true) {
try {
// ...
} catch (Exception e) {
// ...
}
}
And you almost never want to call System.exit. Just break the loop instead.
Is this legal code? Yes.
Is what you have there recommended? No.
If the method throws an exception it's likely recalling it will throw again. See the quote below.
Calling it again in a tight loop without attempting remedy, at least waiting a recovery and counting failures (3 strikes out?) will just end up in a tight loop of failure and stack overflow here.
So:
Can you identify errors that retrying may work and only retry on those?
You should almost certainly include some kind of 'back-off' wait before retry.
Always (always!) include a maximum retry number after which you accept failure.
In my experience the only kind of failure that may work on retry is 'service unavailable' meaning an intermittent outage.
It may not be relevant, but things like (say) invalid credentials aren't going to fix themselves and ideally you don't resubmit those. That's particularly because you end up locking the account and being in an even worse state and possibly causing issues for others using the valid credential...
The other scenario is (say) file not found and you're using the non-existence of a file as a way of polling for something.
That's a poor design pattern and is a misuse of exception handling.
You should strongly prefer to use some kind for existence check in those cases and not let routine activity get confused with exception handling of issues.
Also if you do retry log each attempt (it may be useful later to see whether things are running smoothly or getting delayed in retry scenarios even if the go through eventually). But always differentiate a 'Warning' when retrying and 'Error' when 'throwing in the towel' and failing.
public class Runner {
private static int MAX_RETRIES=3;
private static int BACK_OFF_MILLIS=30000;
public void Run() throws Exception,InterruptedException {
final int TRIES=3;//In reality may be configured.
int trycount=1;
for(;;){
try{
tryRun();
return;
}catch(Exception e){
String message=e.getMessage();
if(trycount>=MAX_RETRIES){
System.out.println("*FAILED*: "+e.getMessage());
throw e;
}
boolean retriable=true;
//Any tests for non-retriable exceptions here...
if(!retriable){
System.out.println("*FAILED*: non-retriable exception - "+e.getMessage());
throw e;
}
++trycount;
System.out.println("Warning: "+e.getMessage()+" retrying "+ trycount+" of "+TRIES);
try {
Thread.sleep(trycount*BACK_OFF_MILLIS);//Some kind of back-off...
}catch(InterruptedException ie){
System.out.println("*FAILED*: Interrupted. Aborting.");
throw ie;
}
continue;
}
}
}
public void tryRun() throws Exception{
//Real workload goes here!
}
}
NB: The back-off strategy here is very simplistic. When it comes to outages then it's usually recommended to implement a random element and an increasing back-off like 1 minute, 10 minutes, 25 minutes. But that's a topic in itself.
I'm not sure who really said but this popular quote seems relevant.
The definition of insanity is doing the same thing over and over again
and expecting different results

why is the Catch exception e printing instead of doing what is in Try

I am confused why it is going to catch and print the error occurred message when I run my code since it runs and just prints the message I can't tell what the error could be
Note: this is my very first time using try and catch my professor told us to use it but haven't really learned how it works fully yet so I'm not sure if the problem is with that or if it's just with my code
public static void main (String [] args) {
try {
File file = new File("in.txt");
Scanner scanFile = new Scanner(file);
...
} catch(Exception e) {
System.out.println("Error");
}
}
Do not catch an exception unless you know what to do. It is common that you don't - most exceptions aren't 'recoverable'.
So, what do you do instead?
Simplest plan: Just tack throws Exception on your main method. public static void main(String[] args) methods should by default be declared to throws Exception, you need a pretty good reason if you want to deviate from this.
Outside of the main method, think about your method. Is the fact that it throws an exception an implementation detail (a detail that someone just reading about what the method is for would be a bit surprised by, or which could change tomorrow if you decide to rewrite the code to do the same thing but in a different way)? In that case, do not add that exception to the throws clause of your method. But if it is, just add it. Example: Any method whose very name suggests that file I/O is involved (e.g. a method called readFile), should definitely be declared to throws IOException. It'd be weird for that method not to throws that.
Occasionally you can't do that, for example because you're overriding or implementing a method from an interface or superclass that doesn't let you do this. Or, it's an implementation detail (as per 2). The usual solution then is to just catch it and rethrow it, wrapped into something else. Simplest:
} catch (IOException e) {
throw new RuntimeException("uncaught", e);
}
Note that the above is just the best default, but it's still pretty ugly. RuntimeException says very little and is not really catchable (it's too broad), but if you don't really understand what the exception means and don't want to worry about it, the above is the correct fire-and-forget. If you're using an IDE, it probably defaults to e.printStackTrace() which is really bad, fix that template immediately (print half the details, toss the rest in the garbage, then just keep on going? That's.. nuts).
Of course, if you know exactly why that exception is thrown and you know what to do about it, then.. just do that. Example of this last thing:
public int askForInt(String prompt) {
while (true) {
System.out.println(prompt + ": ");
try {
return scanner.nextInt();
} catch (InputMismatchException e) {
System.out.println("-- Please enter an integral number");
}
}
}
The above code will catch the problem of the user not entering an integer and knows what to do: Re-start the loop and ask them again, until they do it right.
Just add throws Exception to your main method declaration, and toss the try/catch stuff out.
There are a couple of problems with your current code:
catch (Exception e) {
System.out.println("Error occured...");
}
Firstly, you are not printing any information about the exception that you caught. The following would be better:
catch (Exception e) {
System.out.println(e.getMessage()); // prints just the message
}
catch (Exception e) {
System.out.println(e); // prints the exception class and message
}
catch (Exception e) {
e.getStackTrace(System.out); // prints the exception stacktrace
}
Secondly, for a production quality you probably should be logging the exceptions rather than just writing diagnostics to standard output.
Finally, it is usually a bad idea to catch Exception. It is usually better to catch the exceptions that you are expecting, and allow all others to propagate.
You could also declare the main method as throws Exception and don't bother to catch it. By default, JVM will automatically produce a stacktrace for any uncaught exceptions in main. However, that is a lazy solution. And it has the disadvantage that the compiler won't tell you about checked exceptions that you haven't handled. (That is a bad thing, depending on your POV.)
now null printed out.
This is why the 2nd and 3rd alternatives are better. There are some exceptions that are created with null messages. (My guess is that it is a NullPointerException. You will need a stacktrace to work out what caused that.)
Catching Exception e is often overly broad. Java has many built-in exceptions, and a generic Exception will catch all of them. Alternatively, consider using multiple catch blocks to dictate how your program should handle the individual exceptions you expect to encounter.
catch (ArithmeticException e) {
// How your program should handle an ArithmeticException
} catch (NullPointerException e) {
// How your program should handle a NullPointerException
}

How to use ValueError in catch java

I want to try and catch in java,
when I wrote the catch part it asked me for a parameter,
the parameter I want to use is ValueError (as meaning in python)
Example:
try {
System.out.print("Write your weight: ");
weight = input.nextDouble();
}
catch (ValueError){
System.out.print("You must write your weight in numbers: ");
weight = input.nextDouble();
}
When you are working with java if you use some IDEs(like intllij) it will suggest you what exception(s) you should catch and in this situation or when you know what exceptions you should catch(suppose ExceptionType1 and ExceptionType2) your code will be something like :
try {
//some code with multiple exceptions
} catch (ExceptionType1 ex){
//some code to handle your exceptions
} catch (ExceptionType2 ex){
//some code to handle your exceptions
} ....
but in general if you dont know what exception(s) you have, or you dont want to handle all of them, you could catch general Exception something like this:
try {
//some code with multiple exceptions
} catch (Exception ex){
//some code to handle your exceptions
}
and of course you could write your own exceptions
The nextDouble method of Scanner (which I assume is the type of input) can throw a few exceptions. You can only catch a type of exception that is possible to come back. If you are interested specifically if someone typed a bad answer (like 'yes' instead of a number) then you can catch InputMismatchException. If you're just wanting to capture any error at all you can catch the more generic Exception. In either case your catch statement must name the exception type and a variable name like this:
catch (InputMismatchException ex) { ... }
or
catch (Exception ex) { ... }
This way you can do something with the exception by calling methods on the ex variable.
Also, you show the catch simply trying again. This might work if the user types a bad value once, but not if it happens a second time. A better way to try again would be this:
weight = -1; // so we can tell if a valid weight was given
while (weight < 0) {
try {
System.out.print("Write your weight: ");
weight = input.nextDouble();
}
catch (InputMismatchException ex){
System.out.print("You must write your weight in numbers.");
}
}
This allows the question to be asked until they enter a valid value.

Java - Catching Exceptions Using Class Exception [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have to: create a code that demonstrates how various exceptions are caught: using the code template of:
catch (Exception exception)
Thanks for all of the helpful comments.
I've revised my code:
package exception;
import java.util.Scanner;
import java.io.*;
public class Exception
{
public static void main(String args[])
{
try
{
int a[] = new int[10];
System.out.println("Access element three :" + a[11]);
// The reason this is an exception is because there is no element 11 of the array. It only has 10.
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Exception thrown :" + e);
// This should print out whatever number was requested for a[e]
}
System.out.println("Out of the block");
// Once the exception is caught, this statement will be printed.
}
}
Output:
run:
Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 11
Out of the block
BUILD SUCCESSFUL (total time: 1 second)
Now my question is: Is the format done correctly? The problem requires that I use
catch (Exception exception).
I'm not sure if that's what I did - If not how can I?
Once again, thanks everyone.
The problem is with the syntax of your try-catch block.
It should be as follows:
try {
//Here goes code that might throw an exception.
}
catch(Exception e)
{
//Here goes code to handle if an exception was thrown in the try block.
}
I'm assuming your assignment hander-outer wants you to not just throw and exception with "throw new java.lang.Exception();" But instead to write some code that might throw an exception.
If you want the code to work the way you're doing it, it'll look like this:
try {
java.lang.Exception exception = new java.lang.Exception();
throw exception;
}
catch(Exception e)
{
System.out.println("I caught one!, Here's it's info: ");
e.printStackTrace();
}
However, if you want to do it the correct way, it'll look something like this:
try {
int number = 500;
int result = number / 0;
//This will throw an exception for dividing by zero.
int[] array = new int[10];
int bad = array[11];
//This will throw an ArrayIndexOutOfBoundsException
}
catch(Exception e)
{
System.out.println("I caught one! Here's some info: ")
e.printStackTrace();
}
Of course, with the code above, as soon as the first exception is thrown (by dividing by zero), the catch block will catch it and break out of the try block, so the next bad piece of code isn't ever executed.
I recommend looking here for learning what you need to know for this assignment:
https://docs.oracle.com/javase/tutorial/essential/exceptions/try.html
Also here:
https://docs.oracle.com/javase/tutorial/essential/exceptions/handling.html
And here as well:
http://docs.oracle.com/javase/tutorial/essential/exceptions/
Good Luck!
EDIT
In your catch block, you can use "System.exit(1);" Which will stop your program and have it return 1, which means that it ended its execution with an error.
However, let's say you're wanting to get a user to enter their age. You can prompt them in a try block and in the case that they enter a negative number, you could catch it with an exception and prompt again until they enter a positive number. In that case, you wouldn't want to use System.exit(1) because then your program would stop when it could keep going, all because a user gave a bad input.
That isn't a good example because you shouldn't handle such trivial things, like negative numbers, with an exception. But the idea is the same. If you want your code to continue on, you'll want to handle the error and continue. The only time to use "System.exit(1);" is if your program can't fix the error given, or if your program only did one task and that task couldn't be completed with the given input or encounters an error in doing that task.
This has included some things the other answer forgot, like scriptability (it's a good thing!)
package exception;
//import java.util.Scanner; (unused import)
import java.lang.Exception;
public class ExceptionTester {
public static void main(String[] args) {
try {
throw new Exception("Error Message Here");
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
};
}
}

Error handling with if statement

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");

Categories