Question about how to exit program with exception - java

Assume that I want to exit a console program if the user entered the char f, and in any time of the program.
The user is supposed to enter some info but I want for each step he entering the input to be able to stop all the operation if he entered "f"?
How can I do that?
Should it be something like:
try
{
if (userchoice.equals("F"))
{
throw new exception e;
}
}
catch (exception e)
{
System.exit(1);
}
Thanks

You can throw the exception, unless it is caught it will cause the current thread to die.
if ("f".equalsCaseIgnore(userchoice))
throw new IllegalArgumentException("Option "+userchoice+" not allowed.");

Here's the correct syntax:
try {
if (userchoice.equals("F")) {
throw new Exception();
}
} catch (Exception e){
System.exit(1);
}

Hint:
Scanner class
System.exit();

The input of the char "f" is expected behavior and so throwing an exception may be wrong way.
Encapsulate your input in a method which is responsible to handle the input and decided behavior.
Just call system.exit() here if the user entered "f" or call an exit method that does the work.

Do the following.
Read the input from the command line using classes like BufferedReader or Scanner.
Check for the character "f" from the i/p'ed string.
Throw your exception using throw new MyException();
Catch the exception in the catch block and terminate it with System.exit(1);
If you require "f" or "F", use equalsIgnoreCase() function.
Try something like this,
try{
if (userchoice.equals("F")) {
throw new MyException;
}
}
catch (MyException e) {
System.out.println("MyException caught because i/p character was F" + e);
System.exit(1);
}

Related

An exception is not thrown using throw command

I am coding a method that return an instance of FragmentManager as shown in the code belwo.
the prblem is, I want to throw an exception if the context passed to the method is null and then terminate the App.
what happens is, when I pass null to the method mentioned below, the App closes but the message in the NullPointerException which is :
getFragmentManagerInstance: Context reference is null
is not displayed
please let me know how to throw an exception and terminate the App correctly.
libs:
public static FragmentManager getFragmentManagerInstance(Activity activity) throws Exception {
try {
if (activity != null) {
return activity.getFragmentManager();
} else {
throw new NullPointerException("getFragmentManagerInstance: Context reference is null");
}
} catch (NullPointerException e) {
System.exit(1);
return null;
}
}
Just remove the try block. Simply typing
if (activity != null) {
return activity.getFragmentManager();
} else {
throw new NullPointerException("getFragmentManagerInstance: Context reference is null");
}
will do what you want, since NullPointerException is an unchecked exception.
The message "getFragmentManagerInstance: Context reference is null" is being stored in e. You need to print it to make it display on the screen.
In the catch block, add a print statement before System.exit(1)
catch (NullPointerException e) {
System.out.println(e);
System.exit(1);
return null;
}
is not displayed
Sure, that's because you're swallowing the exception:
} catch (NullPointerException e) {
System.exit(1);
return null;
}
The message is carried in e, and you're not using that in the catch block.
Note that it is almost never the right thing to do to catch a NullPointerException. In this case, you can simply print the message and terminate the app directly:
if (thing == null) {
System.err.println("It's null!");
System.exit(1);
}
Just use e.printStackTrace()
before System.exit(1)
and it will print as you wished
The message is not being displayed because you haven't written any code to print it. If you want to display message, add e.printStackTrace(); before exiting.
In order to print some information you need to provide them to an output stream such as System.out or System.err.
By default if you call ex.printstacktrace() it will print the exception within in System.err.
You can also use ex.printstacktrace(System.out) to choose where you send the information such as a file, the console or any output.
Also your application will immediately stop after the System.exit so your line of code need to be before the exit.
I'm suprised this hasn't been stated yet, change your catch block to
} catch(NullPointerException e){
System.err.print(e.getMessage());
System.exit(1);
return null;
}
And if you want to print a message to the user, consider using a Toast instead of Exception message.

Java: try/catch with InputMismatchException creates infinite loop while reading of a file

I have a task to make a program that will add up all the valid integers in a file and to ignore anything that isn’t a valid int. I have to use Try and Catch.
File Numbers = new File("Numbers.txt");
Scanner readFile = null;
int i = 0;
int total= 0;
boolean success = false;
while(!success){
try {
readFile = new Scanner(Numbers);
while(readFile.hasNext()){
i = readFile.nextInt();
System.out.println(i);
total = i + total;
};
success = true;// Ends The loop
} catch (FileNotFoundException e1) {
System.err.println(Numbers.getName()+" does not exist");
}
catch(InputMismatchException e2){
System.err.println("Data incorrect type expecting an int found: " + readFile.nextLine());
readFile.next();
}
System.out.println("total is: " + total);
};
The problem is that the program gets caught in an infinite loop, where instead of going past the exception it just starts again.The task seems pretty straight forward, yet i don't know why it wont work?
You fall into infinite loop because when exception happens, the success variable didn't change its value to true. In order to do some action even when exception happens you should add the finnaly block. It could look like this:
try {
// do some stuff
} catch (Exception e) {
// catch the exception
} finally {
if (!readFile.hasNext()) success = true;
}
And by the way, never do this: catch (Exception e), I did it just for example sake. Instead always catch the specific exception. Because Exception is the most basic class in the exception hierarchy, so it will catch up all the exceptions, and unless you re-throw it you could have false feeling of "safiness". When you want to catch all the exceptions, you should do this:
try {
// do stuff
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
e.printStackTrace(); // or other approptiate action, i.e. log it.
}
Assume any of the following FileNotFound or InputMismatchException exceptions will raise, then your program wont change success to true. Thus it returns to the outer while loop and read the same file. Because nothing has changed the same Exception will be thrown again.
==> Endless loop.
To fix that I suggest to move the try/catch block to the inner while.

Throwing exception error

My program is not compiling and showing me this error:
System.out.println("Error: "+ e.getMessage());
Scanner scanner = new Scanner(System.in);
try {
int num = scanner.nextInt();
if (num != 0) {
throw new Exception("Not zero");
}
System.out.println("I'm happy with the input.");
} catch (InputMismatchException e) //InputMismatchException is never thrown in body of corresponding try statement
{
System.out.println("Invalid Entry");
} catch (Exception e) {
System.out.println("Error: "+ e.getMessage());
}
The error message is quite clear:
InputMismatchException is never thrown in body of corresponding try statement
You're trying to catch an exception which is guaranteed not to be thrown from the try block. This is useless, and even invalid. Remove the catch (InputMismatchException e) block.
Actually, the try block can throw a java.util.InputMismatchException. So I guess that you're in fact catching an InputMismatchException of another package. Check your imports, and make sure you import java.util.InputMismatchException and not some other com.foo.bar.InputMismatchException.
EDIT:
the error message confirms what I thought. You're catching javaapplication9.InputMismatchException, instead of java.util.InputMismatchException. I'm not sure why you defined your own InputMismatchException.

How to throw exception for statment?

HI !
I want to throw exception for the line
BarcodeNo=Long.parseLong(jTextField1.getText())
I done this in a way
BarcodeNo=Long.parseLong(jTextField1.getText()) throw new NumberFormatException("Enter Numbers Only ");
But this way compiler throws error stating ";" required
So anyone can tell me how to do this ?
Thanks
That will already thrown an exception if the text isn't in the right format. If you want to change the exception message, you'd have to catch the exception and throw a new one:
try {
BarcodeNo = Long.parseLong(jTextField1.getText());
} catch (NumberFormatException e) {
throw new NumberFormatException("Enter Numbers Only");
}
I wouldn't suggest that you try to use exception message as user-visible messages though - they're more reasonable for logging than for showing an end user.
yes you should put
try
{
BarcodeNo=Long.parseLong(jTextField1.getText());
}
catch(Exception e)
{
throw new NumberFormatException("Enter Numbers Only ");
}

Catching some exceptions but ignoring others - why doesn't this work?

I have something similar to this.
void func() {
try {
//socket disconnects in middle of ..parsing packet..
} catch(Exception ex) {
if(!ex.getMessage().toString().equals("timeout") || !ex.getMessage().toString().equals("Connection reset")) {
debug("Exception (run): " + ex.getMessage());
ex.printStackTrace();
}
}
Why is it that when I get a connection reset exception or a timeout exception, it still goes inside the condition. I tried without toString and with no luck.
You shouldn't catch all exceptions and then test the error message of the exception. Instead only catch those exceptions that you intend to handle - for example SocketTimeoutException.
catch (SocketTimeoutException ex)
{
// Do something...
}
With your current code you may be catching some other type of exception that you weren't expecting. Currently you will just ignore this exception, not even logging it. This can make it very difficult to debug what is going on. If you have an exception that you can't handle you should either rethrow it or log it.
I want to catch all exceptions
If you really want to do that then you can write your code as follows:
catch (SocketTimeoutException ex)
{
// Do something specific for SocketTimeoutException.
}
catch (Exception ex)
{
// Do something for all other types of exception.
}
Regarding your specific error, you have written:
!a.equals(b) || !a.equals(c)
This expression always evaluates to true. What you meant was:
!a.equals(b) && !a.equals(c)
Or equivalently:
!(a.equals(b) || a.equals(c))
Note that by rewriting your code as I suggested above you completely avoid having to write this complicated boolean expression.
It's really not safe to rely on exceptions messages to know what is the cause of your exception.
In your case you can try to catch more specific exceptions, such as SocketTimeoutException and the classic IOException :
void func() {
try {
//socket disconnects in middle of ..parsing packet..
} catch(SocketTimeoutException ex) {
//In case of Time out
} catch(IOException ex){
//For other IOExceptions
}
}
Sources :
[Socket.connect()][3]
Even if you prefer to seek informations in exceptions messages, you shouldn't check if the message simply is equal to "timeout" but if the message contains "timeout"
[3]: http://download-llnw.oracle.com/javase/6/docs/api/java/net/Socket.html#connect(java.net.SocketAddress, int)

Categories

Resources