Throwing exception error - java

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.

Related

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.

Exception handling compile error: Exception; must be caught or declared to be thrown

Im not sure why I am getting this error and have a feeling im missing something obvious here. It occurs on the line: Verify.Validate(number); with the error: Program5.java:23: error: unreported exception Exception; must be caught or declared to be thrown. Any suggestions would be appreciated.
-Chris
import java.util.Scanner;
public class Program5
{
public static void main(String[] args)
{
// The driver class should instantiate a Verify object with a range of 10 to 100.
Verify Verify = new Verify(10, 100);
//Prompt the user to input a number within the specified range.
System.out.print("Input a number between 10-100: ");
// Use a Scanner to read the user input as an int.
Scanner input = new Scanner(System.in);
int number = input.nextInt();
// Use Try/Catch to test number
try
{
Verify.Validate(number);
System.out.println("Number entered: " + number);
}
catch (NumberNegativeException ex)
{
System.out.println(ex.getMessage());
}
catch (NumberLowException ex)
{
System.out.println(ex.getMessage());
}
catch (NumberHighException ex)
{
System.out.println(ex.getMessage());
}
}
}
As per your code there are 3 types of exception your validate(int) method may throw :
1) NumberHighException
2) NumberLowException
3) NumberNegativeException
So the code for your validate(int) method may look like this :
public void validate(int number) throws NumberHighException, NumberLowException,
NumberNegativeException {
if(number > 100)
throw new NumberHighException("Number is High");
if(number < 10)
throw new NumberLowException("Number is Low");
if(number < 0)
throw new NumberNegativeException("Number is Negative");
else
System.out.println("Your Entered Number is valid");
}
Now , while compiling your code, you are getting Error at:
catch (NumberNegativeException ex) // Line no 23, where you are getting the error
{
System.out.println(ex.getMessage());
}
And the error generated is :
error: unreported exception Exception; must be caught or declared to be thrown
This indicates that the exception thrown is of higher(Super class) Type than as specified with the catch blocks.
So, somewhere in your validate() method , you're throwing an exception of type Exception. Just Correct it and you will be fine.
Lets try using a more general catch:
try{
....
}catch(Exception e){
}
In this way you caught all the errors since every error extends the class Error

Java exception: why my program is not terminating?

When I run my simple code and enter char instead of integer value which was supposed to be Entered.
Program, listed below is supposed to be terminated after printing "error please Enter integer value".
But this code, also printing the line after Occurrence of error
import java.util.InputMismatchException;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
System.out.println("enter value integer ");
Scanner sn = new Scanner(System.in);
try{
int a = sn.nextInt();
} catch (InputMismatchException ex){
System.out.println("error please enter integer value");
}
System.out.println("not terminating");
}
}
But this code, also printing the line after Occurrence of error
Because it is out side of try-catch, that is the advantage of exception handling.
Exception handling prevents the abnormal termination of program due to run time error. And that is what happened.
See also
exception handing docs
It is terminating, it just prints out the System.out first. This is as expected - it jumps into the catch block, and then continues.
System.out.println("enter value integer ");
Scanner sn = new Scanner(System.in);
try {
int a = sn.nextInt();
} catch (InputMismatchException ex) {
System.out.println("error please enter integer value");
// you are catching input mis match here
// exception will catch and program continues
}
System.out.println("not terminating"); // this is out side the try-catch
So you will get this line in your out put too.
After entering the catch block, flow continues on, so the next line to execute is the bottom print.
If you want to terminate from within the catch:
try {
int a = sn.nextInt();
} catch (InputMismatchException ex) {
System.out.println("error please enter integer value");
return; // program will end
}
If you want it to be terminated you need to re-throw the exception e.g.:
System.out.println("enter value integer ");
Scanner sn = new Scanner(System.in);
try {
int a = sn.nextInt();
} catch (InputMismatchException ex) {
System.out.println("error please enter integer value");
throw new RuntimeException(ex);
}
System.out.println("not terminating"); // this is out side the try-catch
That way the last system output would not be printed and you would get a stacktrace instead.

Question about how to exit program with exception

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

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

Categories

Resources