I'm trying to throw an exception (without using a try catch block) and my program finishes right after the exception is thrown. Is there a way that after I throw the exception, to then continue execution of my program? I throw the InvalidEmployeeTypeException which I've defined in another class but I'd like the program to continue after this is thrown.
private void getData() throws InvalidEmployeeTypeException{
System.out.println("Enter filename: ");
Scanner prompt = new Scanner(System.in);
inp = prompt.nextLine();
File inFile = new File(inp);
try {
input = new Scanner(inFile);
} catch (FileNotFoundException ex) {
ex.printStackTrace();
System.exit(1);
}
String type, name;
int year, salary, hours;
double wage;
Employee e = null;
while(input.hasNext()) {
try{
type = input.next();
name = input.next();
year = input.nextInt();
if (type.equalsIgnoreCase("manager") || type.equalsIgnoreCase("staff")) {
salary = input.nextInt();
if (type.equalsIgnoreCase("manager")) {
e = new Manager(name, year, salary);
}
else {
e = new Staff(name, year, salary);
}
}
else if (type.equalsIgnoreCase("fulltime") || type.equalsIgnoreCase("parttime")) {
hours = input.nextInt();
wage = input.nextDouble();
if (type.equalsIgnoreCase("fulltime")) {
e = new FullTime(name, year, hours, wage);
}
else {
e = new PartTime(name, year, hours, wage);
}
}
else {
throw new InvalidEmployeeTypeException();
input.nextLine();
continue;
}
} catch(InputMismatchException ex)
{
System.out.println("** Error: Invalid input **");
input.nextLine();
continue;
}
//catch(InvalidEmployeeTypeException ex)
//{
//}
employees.add(e);
}
}
If you throw the exception, the method execution will stop and the exception is thrown to the caller method. throw always interrupt the execution flow of the current method. a try/catch block is something you could write when you call a method that may throw an exception, but throwing an exception just means that method execution is terminated due to an abnormal condition, and the exception notifies the caller method of that condition.
Find this tutorial about exception and how they work - http://docs.oracle.com/javase/tutorial/essential/exceptions/
Try this:
try
{
throw new InvalidEmployeeTypeException();
input.nextLine();
}
catch(InvalidEmployeeTypeException ex)
{
//do error handling
}
continue;
If you have a method that you want to throw an error but you want to do some cleanup in your method beforehand you can put the code that will throw the exception inside a try block, then put the cleanup in the catch block, then throw the error.
try {
//Dangerous code: could throw an error
} catch (Exception e) {
//Cleanup: make sure that this methods variables and such are in the desired state
throw e;
}
This way the try/catch block is not actually handling the error but it gives you time to do stuff before the method terminates and still ensures that the error is passed on to the caller.
An example of this would be if a variable changed in the method then that variable was the cause of an error. It may be desirable to revert the variable.
Related
why flow continue after exception catch? when i click button, toast show me message but after flow continue....
I show you my code!
public static int showResult2(View v) {
int totalAmount = 0;
for (Birra b : biAdapter.getBox()) {
if (b.selected) {
try {
int quantitaInt = Integer.parseInt(b.getQuantità());
totalAmount += b.distance * quantitaInt;
}catch(NumberFormatException exc){
System.out.println(exc);
Toast.makeText(context, "inserisci una quantita' a \""+b.name, Toast.LENGTH_LONG).show();
break;
}
}
}
return totalAmount;
}
IN ANOTHER CLASS I RECALL THE METHOD:
ThreeFragment tf = new ThreeFragment();
string4 = tf.showResult(v);
try {
totalebibite = tf.showResult2(v);
} catch (NumberFormatException exc) {
exc.printStackTrace();
}
You've caught the exception, so Java assumes that you are going to deal with it adequately.
If you don't want that behaviour, aside from not catching it at all, you could always rethrow the exception (throw exc;) after you've printed your message, which means that something higher up the call stack ought to deal with it, or use a break; statement to end the loop early.
If you want to break your loop in exception use like the below.
You should add your break; in catch
break; is what you need to break out of any looping statement like for, while or do-while.
Still if it's comes meant make sure you are not calling this method again and again.
Also check in your Java class that you have any other method is using the same for loop condition.
You should not call your fragment classes. It's a wrong way to call a method.
ThreeFragment tf = new ThreeFragment();
string4 = tf.showResult(v);
totalebibite = tf.showResult2(v);
It's a static method call your method in this way
ThreeFragment.showResult2(v);
Check this showResult(v); has the same for loop
The below piece of code is similar to what you have presented. As pointed by others, break; ends the nearest loop.
for(int i=0; i<10; i++) {
if(true) {
try{
//Your logic here, which could throw exception
System.out.println("throwing");
if(true) {
throw new Exception("This is it");
}
}catch(Exception e){
System.out.println("catching");
break;
}
System.out.println("inside if");
}
System.out.println("inside for");
}
System.out.println("outside for");
Using break is a bad programming practice. You could change the flow of code to something like this.
try{
System.out.println("inside try");
for(int i=0; i<10; i++) {
if(true) {
if(true) {
throw new Exception("This is it");
}
System.out.println("inside if");
}
System.out.println("inside for");
}
}
catch(Exception e){
System.out.println("catching");
}
System.out.println("after catch");
Please mark your question as answered, if you see it is answered.
Put your try/catch block around the loop instead of inside, so the loop exits on an exception:
try {
for (Birra b : biAdapter.getBox()) {
if (b.selected) {
int quantitaInt = Integer.parseInt(b.getQuantità());
totalAmount += b.distance * quantitaInt;
}
}
} catch (NumberFormatException exc) {
System.out.println(exc);
Toast.makeText(context, "inserisci una quantita' a \""+b.name, Toast.LENGTH_LONG).show();
}
Alternatively, inside the catch block you can a) rethrow the exception, b) break out of the loop, or c) return from the method.
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.
do {
try {
for(int i=c;i<no;i++){
System.out.println("enter barcode :");
isbn = input.next();
System.out.println("yearOfPub :");
yearOfPub = input.nextInt();}
loop =false;
}
catch (InvalidISBN_EXCEPTION e) {
// throw new InvalidISBN_EXCEPTION(isbn);
System.err.printf(" Error %s", e);
System.out.println("wrong ISBN");
loop = true;
}
} while(loop);
i have class store and class InvalidISBN_EXCEPTION
and i try to catch this error how i can fix it ?
Unless something in this code (your try block)
for(int i=c;i<no;i++){
System.out.println("enter barcode :");
isbn = input.next();
System.out.println("yearOfPub :");
yearOfPub = input.nextInt();}
loop =false;
declares that it will throw a checked Exception of type InvalidISBN_EXCEPTION, the compiler will complain. You are saying you can catch that error but nothing ever declares it will throw it. You have to remove the try/catch code around the code.
Please have a look at mine constructor below, I'm creating a Fraction from a String:
public Fraction(String str)
{
if(str.isEmpty())
{
throw new IllegalArgumentException("The str (String) parameter cannot be empty!");
}
int[] fractionData= new int[2];
String[] data = str.split("/");
try
{
if(data.length==0)
throw new IllegalArgumentException("The str (String) parameter cannot be empty");
}
catch (IllegalArgumentException ex)
{
System.out.println(ex.toString());
}
try
{
fractionData[0] = Integer.parseInt(data[0]);
}
catch (IllegalArgumentException ex)
{
System.out.println(ex.toString());
}
try
{
fractionData[1] = Integer.parseInt(data[1]);
if(fractionData[1]==0) throw new ArithmeticException("Denominator can't be 0");
}
catch (ArithmeticException ex)
{
System.out.println(ex.toString());
}
fractionData = normalize(fractionData[0],fractionData[1]);
this.numerator = fractionData[0];
this.denominator = fractionData[1];
}
I'm catching the IllegalArgumentException fine, but fail to catch the ArithemticException. I can test both successfully
#Test(expected=IllegalArgumentException.class)
public void testIllegalArgumenException() throws IllegalArgumentException
{
Fraction g = new Fraction("");
}
#Test(expected=ArithmeticException.class)
public void testArithmeticException() throws ArithmeticException
{
Fraction g = new Fraction(1/0);
}
Thanks the comments from #xp500 I've changed my code to:
public Fraction(String str)
{
if(str.isEmpty()) throw new IllegalArgumentException("The str (String) parameter cannot be empty!");
int[] fractionData= new int[2];
String[] data = str.split("/");
if (data.toString().matches("[a-zA-Z]+")) throw new NumberFormatException("only numbers allowed in the string");
fractionData[0] = Integer.parseInt(data[0]);
fractionData[1] = Integer.parseInt(data[1]);
if(fractionData[1]==0) throw new ArithmeticException("Denominator can't be 0");
fractionData = normalize(fractionData[0],fractionData[1]);
this.numerator = fractionData[0];
this.denominator = fractionData[1];
}
It doesn't quote "only numbers allowed in the string", but stops initializing the Fraction as 0/0 in case String with letters is used to initialize the Fraction and throws the other exceptions with quoted text. The lesson for me is: DON'T CATCH EXCEPTIONS UNLESS YOU'RE ACTUALLY DOING SOMETHING WITH THEM
Yo are catching ArithmeticException but you are not retrowing it(like other exceptions)
A couple of comments about the code.
Your usage of the exceptions is making the code unreadable and hard to follow. You should try to use less try catch blocks. I think it would be better if you wrote something along the lines of
if (data.length==0) {
System.out.println(ex.toString());
throw new IllegalArgumentException("The str (String) parameter cannot be empty");
}
and not catch that exception, since you want to tell the caller that an exception occured.
Also, fractionData[0] = Integer.parseInt(data[0]); throws a NumberFormatException, not IllegalArgumentException
The ArithmeticException isn't being thrown since you are catching it inside the constructor, and not rethrowing it. Please note that, after catching it, your fraction will be initialized in an invalid state, since
fractionData = normalize(fractionData[0],fractionData[1]);
this.numerator = fractionData[0];
this.denominator = fractionData[1];
will be executed. Again, you might want to rewrite those lines for something like
if(fractionData[1]==0) {
System.out.println(ex.toString());
throw new ArithmeticException("Denominator can't be 0");
}
You don't need to write throws Exception, in your test methods, since you are expecting an exception to be thrown, the method itself won't throw that exception.
I hope that helps!
I am checking if number the user entered is Zeckendorf and I want to display an exception if it is not, how do i do that? Also how do I convert the Zeckondorf to its decimal equivalent?
import java.util.Scanner;
public class IZeckendorfNumberConvertor {
static String number;
int zeckonderEquivalent;
static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
convertToZeckonderNumber();
isTrueZeckonderNumber();
}
private static boolean isTrueZeckonderNumber() {
System.out.println("Enter a Zeckonder Number:");
number = scanner.nextLine();
if (number.equals("10100"))
{
return true; }
else if (number.equals("010011") || number.equals("010100"))
{
return false; }
return false;
}
private static void convertToZeckonderNumber() {
}}
I advise you not to display an exception (i.e. trace and such) as it is very user Unfriendly.
You can use the throw syntax to throw a proper exception :
throw new Exception("Given number is not a Zeckendorf number");
but be sure to catch it and display a nice and clean message :
try {
// Your input code goes here
} catch (Exception e) {
System.out.println(e.getMessage());
}
Another easier option will be to just check the return value of the method and print the results accordingly.
I will recommend to use the latter solution as exceptions are used when something bad and unexpected happens in your program and you want to handle it gracefully. In your case the behavior is expected (i.e. user giving a wrong number) so checking the return value will be much clean and easier.
Use try catch block for catch an exception
try {
} catch (Exception e) {
e.printStackTrace();
}
Also use throw for throw a new exception
Assuming to really do want to display the exception, and not a more user friendly message, the first step is probably to get the exception as a string. Then you can do what you like with that string (echo to console, place in a javax.swing.JTextArea, email it, etc).
If you just want the message from the exception, then getMessage() will do:
try { ... }
catch(FooException e) {
String msg = e.getMessage();
}
However, if you want the whole exception, stack trace and all, you'll want something like this:
public static String stackTrace(Exception e) {
StringWriter w = new StringWriter();
e.printStackTrace(new PrintWriter(w));
return w.toString();
}
// ...
try { ... }
catch(FooException e) {
String st = stackTrace(e);
}
If you just want to echo the full stack trace to the console, there is the printStackTrace(), no-arg method:
try { ... }
catch(FooException e) {
e.printStackTrace();
}
If you want to take more control of the presentation of the stack trace you can get the details with:
try { ... }
catch(FooException e) {
StackTraceElement[] stes = e.getStackTrace();
// Do something pretty with 'stes' here...
}
You can just print a error message to the user saying that the input is wrong using a simple if.
if(yourCondition){
// Happy scenario
// Go shead
}else{
// Error Scenario
System.out.println("Error. Invalid Input.");
// If you persist to throw an exception, then you can do something like this
// throw new Exception("Exception Explanation"); // I've commented this, but you can uncomment it if needed
// But the advice is to display an error message, than throw a exception.
}
And regarding the conversion, you can convert binary to decimal like this
int i = Integer.parseInt(binaryString, 2); // 2 indicates the radix here, since you want to convert from binary.
With this code snippet you can convert the String into an integer :
int numberAsInt;
try {
numberAsInt = Integer.parseInt(number);
} catch (NumberFormatException e) {
//Will throw an Exception
}
If you want to create your own Exception class, you can do it like shown here or just throw a RuntimeException with
throw new RuntimeException("Your Message");
My opinion, you can try some thing like following
public static void main(String[] args) {
if(!isTrueZeckonderNumber()){
// your message should goes here
System.out.println("Your message");
}
}
If you really want to throws an exception do following
private static boolean isTrueZeckonderNumber() throws Exception{
System.out.println("Enter a Zeckonder Number:");
number = scanner.nextLine();
if (number.equals("10100")) {
return true;
} else{
throw new Exception("your message");
}
}
What do you mean you want to display an exception?
I would suggest just giving the user feedback instead, as exceptions are used more commonly for EXCEPTIONAL actions that are not supposed to happen.
However if you do want to, you can print a message explaining what happened.
try {
} catch (Exception e) {
System.out.println(e.getMessage());
}