Show message error in java

How can I print error messages from my function when the arguments are invalid?

I just started to learn Java. There is a course in MIT and there is an assignment to write a class for pay calculation. Part of the task is:

  • The base pay must not be less than the minimum wage ($8.00 an hour). If it is, print an error.
  • If the number of hours is greater than 60, print an error message.

The code I have written is as follows:

public class fooCorporation < private float totalPay; private float calc; public float totalPay(double basePay, int hours)< if(hours else if(hours > 40) < int extraHours = hours - 40; float payForFortyHours = (float) (basePay * hours); float payForextraHours = (float) (basePay * 1.5 * extraHours); totalPay = payForFortyHours + payForextraHours; >return totalPay; > public static void main(String[] args) < fooCorporation foo = new fooCorporation(); System.out.println("employee 1: " + foo.totalPay(7.50,35)); System.out.println("employee 2: " + foo.totalPay(8.20,47)); System.out.println("employee 3: " + foo.totalPay(10.00,73)); >> 

The problem I am facing is how to print an error message from the function totalPay() when some conditions are not met. Can the above logic be written in a different way?

So. you can see how to print things, from main(). You could do similar things in totalPay(). What are you asking?

8 Answers 8

The totalPay() method looks good as written. What you could do now is add another method that handles all of the printing. Here’s some code that shows the overall idea. I’ve left gaps in there for you to fill in.

public void printPay(int employeeNum, double basePay, int hours) < if (. ) < System.out.println("error"); >else if (. ) < System.out.println("different error"); >else < System.out.println("employee X: " + totalPay(. )); >> public static void main(String[] args)

The nice thing about using the totalPay() function you already wrote is that it organizes the code in nice, small, manageable chunks. One function does calculations and the other handles printing. Each function has its unique role.

Читайте также:  Таблицы

I suppose you should handle a negative number of hours passed in; for example:

public float totalPay(double basePay, int hours) throws Exception < < if(hours<0) throw new Exception("Hours cannot be a negative number"); if(basePay<=0) throw new Exception("Base pay cannot be a negative number"); . //the rest of the implementation >

HOWEVER, throwing Exception as above is generally bad practice.. Defining your own Exception class and throwing specifically that Exception, when necessary (for example when a standard Java Exception does not perfectly fit in the situation at hand), is a best practice because it gives more useful information as to what had gone wrong on the program and gives the developer a chance to react in an easier, cleaner and more granular way to the specific situation. For example, some Exceptions may be considered fatal while others may be catched and easy to recover from. In cases where it makes sense to define your own Exception as opposed to using one of the Java’s standard library is the following:

class BadParameterException extends Exception < public BadParameterException(String msg)< super(msg); >> 

And in your specific example you could flag your method as throws BadParameterException as so:

public float totalPay(double basePay, int hours) throws BadParameterException < if(hours<0) throw new BadParameterException ("Hours cannot be a negative number"); . // and so on >

you should NEVER throw Exception , this is terrible advice for someone learning Java. And InvalidParameterException should be IllegalArgumentException which is already a standard Exception available in the JDK and what is used by all the Standard library code.

It’s a good practice to write your own exceptions when you need them, but this seems like a duplicate of IllegalArgumentException. The only purpose would be that it’s a checked exceptions, if you really want this.

@JarrodRoberson I think I know what you meant but I also see that your problem is really reading comprehension more than anything else. Didn’t I say that it is a good practice to DEFINE your OWN Exception and THROW THAT EXCEPTION? DIDN’T I provide an EXAMPLE of HOW TO DO THAT?

You generally don’t print things in the middle of general purpose functions since (1) it’s annoying to the people using those functions; and (2) it gives no indication of a problem to the calling code.

Usually, you would either throw an exception or have some specific return code indicating an error condition.

Then the caller can decide what to print (or do otherwise if printing is not appropriate).

For example, if you can determine that the total pay should always be positive, just return -1.0 for an error condition. For example:

public class fooCorporation < public float totalPay (double basePay, int hours) < if (hours < 0) return -1.0; if (hours public static void main(String[] args) < fooCorporation foo = new fooCorporation(); float pay = foo.totalPay (7.50, 35); if (pay < 0) System.out.println ("employee 1: invalid hours"); else System.out.println ("employee 1: " + pay); pay = foo.totalPay (8.20, 47); if (pay < 0) System.out.println ("employee 2: invalid hours"); else System.out.println ("employee 2: " + pay); pay = foo.totalPay (10.00, -4); if (pay < 0) System.out.println ("employee 3: invalid hours"); else System.out.println ("employee 3: " + pay); >> 

That method of yours, by the way, gives you double time and a half ( x2.5 ) for overtime since you’re not adjusting the base hours down to 40. Make sure that’s what you want rather than time and a half ( x1.5 ).

I would emphasize exceptions more strongly. Error codes should be reserved for when invalid input is expected and not a programming error. (i.e. String.indexOf )

Some people prefer to leave exceptions for truly exceptional conditions such as terminal input errors or comms issues. They do not subscribe to the «invalid input parameter is an exception» way of thinking. You could go either way in my opinion. In any case, the return code is an example, not a definitive solution.

if (!someConditions) throw new IllegalArgumentException("Condition XY not met.") 

In main: surround your code with a try-catch-block

try < fooCorporation foo = new fooCorporation(); System.out.println("employee 1: " + foo.totalPay(7.50,35)); System.out.println("employee 2: " + foo.totalPay(8.20,47)); System.out.println("employee 3: " + foo.totalPay(10.00,73)); >catch(IllegalArgumentException ex)

Note: read the link I posted, exceptions can be a little bit confusing, but it’s a very important concept in Java.

For further reading (once you now the basics) I would recommend Exception Handling Antipatterns. It covers some common mistakes regarding exceptions.

The idiomatic way to deal with this would be to test for what ever bad data you might encounter and to throw IllegalArgumentException ( with a very detailed explanation of what was illegal and why ) or one of the other built in exceptions dealing with generic problems with invalid data.

You could also create your own sub classes of RuntimeException for more specific cases. Like BasePayLessThanZeroException or HoursLessThanZeroException or HoursGreaterThan168Exception .

The most important take away is that the cause and possible remedies of the exceptions should be well stated a clear. FILE NOT FOUND without listing the location and name of the file you were looking for is terrible. Could not find ~/settings.xml is a much better exception message.

There’re a few ways to go about this. The approach you take depends upon your requirements. If you merely want to print an error message, you can check your conditions and use System.out or System.err to emit your message:

if (conditionsNotMet) System.err.println("Error: Condition X is not met"); 

Take a look at the javadoc for System.out and System.err (http://download.oracle.com/javase/1,5.0/docs/api/java/lang/System.html) — They’re both output streams, corresponding to stdout and stderr. stderr is typically used for emitting error and log messages, but how each of these outputs is used is up to you, the developer.

If you wanted to abort processing, you might consider using an exception instead:

if (conditionsNotMet) throw new Exception("Condition X is not met"); 

Consider that exceptions can be a burden on developers. Checked exceptions (http://www.javapractices.com/topic/TopicAction.do?Id=129) must be declared to be thrown or caught. In this case, perhaps that’s what you want.

It’s bad form to throw a java.lang.Exception — seriously consider an exception that is more suited (such as IllegalArgumentExeception, in this case) or implement your own. IllegalArgumentException is not a checked exception which might be good in your case. As I mentioned, checked exceptions must be declared as thrown or caught in a try/catch block. Seeing as IllegalArgumentException is not checked, you won’t be forcing clients of your method to catch it.

Often it’s still a good idea to document when a method throws an unchecked exception, though. This informs other developers using your code the common conditions under which an exception is thrown allowing them to make a decision about catching or ignoring the exception.

Источник

How to show an error message in java in a friendly way

I have a question as i am a beginner in java you may find it silly. I am writing a method to read a file and when it does not exist an error just show up.

File f = new File(FILE_path); if (f.exists() && f.canRead()) < try < //Do something >catch (IOException e) < e.printStackTrace(); LOGGER.error("Error message: " + e.getMessage()); >> else
 Exception in thread "main" java.io.FileNotFoundException: /home/project/file_path (No such file or directory) at java.io.FileInputStream.open(Native Method) at java.io.FileInputStream.(FileInputStream.java:146) 

Now my question is that is there anyway that the program does not freeze at this level and we show only the friendly message? or we cannot avoid that and this Exception error always show up even we use try and catch?

Don’t print the stack trace? Don’t halt the program if the operation fails? It’s not clear what you’re asking.

Because you show nothing that would «freeze». There’s no context around your question: if you don’t want to show the «unfriendly» stack trace then don’t print it—you print it. Don’t want it to freeze? No clue—there’s nothing here that would «freeze», it would just exit. That’s why it’s not clear.

2 Answers 2

you could always use joptionpanes:

File f = new File(FILE_path); if (f.exists() && f.canRead()) < try < //Do something >catch (IOException e) < JOptionPane.showMessageDialog (null, "Something went Wrong", "Title", JOptionPane.ERROR_MESSAGE); LOGGER.error("Error message: " + e.getMessage()); >> else

is there anyway that the program does not freeze at this level and we show only the friendly message?

Yes. Your IDE (eclipse or whatever) probably automatically placed e.printStackTrace(); on the line after catch (IOException e) but you don’t need to do this. And more experienced programmers would say it’s completely unnecessary.

When you catch an exception in Java, you are getting control back after an Exception occurs. You can do absolutely anything after a catch that you can do at any other point in your program. You don’t need to print the stack trace.

Sounds like you just want this:

Edit if that is all you have in your catch block, then that is the only thing that will happen after an exception. Your program won’t proceed out/down past the catch block.

Источник

How to display a detailed error message using try< >catch() < >blocks

Suppose in your program you might get an IndexOutOfBoundsException. i am handling it in the following way:

try< //throws an IndexOutOfBoundsException during runtime >catch(IndexOutOfBoundsException ex)

This will only display java.lang.IndexOutOfBoundsException. But I would like to display a detailed error message (which won’t terminate the program), like the one that java gives us (lineNumber, fileName, etc) when we do not handle the error and thus terminates the program.

4 Answers 4

In Java you can use printStackTrace on any exception object to get the stack trace printed by Java. In your case a minimal:

try < // Throw an IndexOutOfBoundsException >catch (IndexOutOfBoundsException ex)

This prints the stack trace to System.err . You can also pass it a print stream or even System.out to print to that particular stream.

Additionally, if you use java logger, you can use:

Use ex.printStackTrace() method to print the exception:

try < int[] x = new int[1]; x[2] = 5; >catch (IndexOutOfBoundsException ex) < ex.printStackTrace(); >System.err.println("Program completed successfully"); 

If you are running in an environment where console output is not desirable, call ex.getStackTrace() , and display elements in a way that is consistent with the user interface of your program.

this was very helpful brother 🙂 but this prints out too much information. I would like the error message to be like the one java gives. java.lang.ArrayIndexOutOfBoundsException: 6 at sth.main(sth.java:15) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:266)

Источник

How to open warning/information/error dialog in Swing?

And you can also change the symbol to an error message or an warning. E.g see JOptionPane Features.

Make sure you dispose the frame, or pass null as the frame. If you don’t it could hold your process open.

import javax.swing.JFrame; import javax.swing.JOptionPane; public class ErrorDialog < public static void main(String argv[]) < String message = "\"The Comedy of Errors\"\n" + "is considered by many scholars to be\n" + "the first play Shakespeare wrote"; JOptionPane.showMessageDialog(new JFrame(), message, "Dialog", JOptionPane.ERROR_MESSAGE); >> 
JOptionPane.showOptionDialog JOptionPane.showMessageDialog . 

Have a look on this tutorial on how to make dialogs.

Just complementing, you can use static imports to give you a hand, making the code cleaner, like this:

import static javax.swing.JOptionPane.*; public class SimpleDialog() < public static void main(String argv[]) < showMessageDialog(null, "Message", "Title", ERROR_MESSAGE); >> 

plz if you are going to tell people something like «It’s kind of obvious», just don’t bother writing an answer. nobody knows the exact same things you do and neither does anybody have to.

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.21.43541

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Оцените статью