I am trying to make a program which allows the user to enter 2 integers (marks).
In case the user doesn't enter an integer, I am creating a try and catch code.
The problem is that after I try to enter letters instead of numbers, there is an error coming out but the program carries on, saying that I didn't pass. How do I let the program stop after saying to the user that he entered a wrong mark?
Here is my code:
public void actionPerformed(ActionEvent e)
try{
myCalculator.setCWK(Integer.parseInt(courseEnter));
myCalculator.setExam(Integer.parseInt(examEnter));
}
catch (Exception a){
System.out.print("System error");
}
displayArea.setText("" + myCalculator.calculateModuleMark());
if(myCalculator.hasPasssed()==true)
{
displayArea.setText(myCalculator.getModuleCode() + "Congratulations! You have PASSED! With a score of " + myCalculator.calculateModuleMark() + "%");
getContentPane().setBackground(Color.green);
}
else
{
displayArea.setText("I am sorry");
getContentPane().setBackground(Color.red);
}
}
If you want the program to "stop" after a certain statement, System.exit(0) is your friend. So, in your catch statement, you could have
catch (Exception a){
System.out.print("System error");
System.exit(0);
}
Note that this is different than return, as System.exit(0) will completely stop your program flow, not just this specific method.
After printing out an error simply type return.
The try...catch blocks means
if an error occurs in the try instruction block, execute the catch instruction block
In your case, you're not exiting the function in your catch block, so it will carry on.
Exception handling is essentially done to prevent the code from exiting abruptly without any error message.
You can just call System.exit(1) after System.out.print("System error").
Note: System.exit(0) means program terminated as expected while any other error code within bracket means there was an error.
So, now your code will be:
public void actionPerformed(ActionEvent e){
try{
myCalculator.setCWK(Integer.parseInt(courseEnter));
myCalculator.setExam(Integer.parseInt(examEnter));
}
catch (Exception a){
System.out.print("System error");
System.exit(1);
}
displayArea.setText("" + myCalculator.calculateModuleMark());
if(myCalculator.hasPasssed()==true)
{
displayArea.setText(myCalculator.getModuleCode() + "Congratulations! You have PASSED! With a score of " + myCalculator.calculateModuleMark() + "%");
getContentPane().setBackground(Color.green);
}
else
{
displayArea.setText("I am sorry");
getContentPane().setBackground(Color.red);
}
}
Related
public static void main() {
String fileName = "cardNumbers.txt";
String line = null;
try {
FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null)
{
CreditCard card = new CreditCard(line);
if (card.creditCardType().equalsIgnoreCase("Unknown"))
{
System.out.println("Card number " + card.getCardNumber() + "is an unknown credit card type.");
}
else if (card.isValid())
{
System.out.println(card.creditCardType() + " number" + card.getCardNumber() + " is valid.");
}
else if (!card.isValid())
{
System.out.println(card.creditCardType() + " number " + card.getCardNumber() + " is not valid.");
}
}
}
catch (FileNotFoundException ex)
{
System.out.println("file not found exception thrown");
}
catch (IOException ex)
{
System.out.println("error while reading the file");
}
finally
{
System.exit(0);
}
}
When I run this method it just says ProcessCardNumbers.main(); VM Terminated. Instead of actually printing out the content.
If I add a print at the very start of the function or in the finally block, they are printed.
Im not sure why this is happening or how I can fix it.
As you told us that:
Adding a println at the start is printed
and
Adding a println in the finally works too
we can deduce that your code is working. It's just that when you reach while((line = bufferedReader.readLine()) != null), line stays null, so you never enter your while.
Why is that? Well, your file may be empty to begin with. If it is not, double-check the encoding of your file: it may not be using the proper returns symbols, hence not having a "completed line".
This seems that in your text file cardNumbers.txt has no data. When this program will execute within while loop bufferedReader.readLine()). will return null. So loop will terminate. After termination you have written System.exit(0); function in finally block which terminate JVM on the spot. So JVM is terminated now that's why you are not able to see anything after working of this code.
If you want to check working, write one SOP statement in finally block. Probably that will execute without termination of JVM.
The problem here is not the bug in your code but the design problem that does not let you see the bug.
You are probably getting an undeclared exception (RuntimeException) and the VM can't print it because you kill it before in the finally.
You have several options:
Remove the System.exit(0); and let it die normally. This may fail if there is another non-daemon thread running. You may try to stop it. You can, for example, cancel a Timer.
Add a catch (RuntimeException e) { section before the finally and print the captured error. e.printStackTrace(); should do the trick.
With any of those you should see the exception on console so you can fix it.
Your main method signature must look like this:
public static void main(String[] args)
instead of
public static void main()
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){
System.err.println(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.
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) {
ex.printStackTrace();
}
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:
logger.log(<LOG_LEVEL>, <LOG_MESSAGE>, ex);
to log the exception. For more details see: https://docs.oracle.com/javase/7/docs/api/java/util/logging/Logger.html
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");
Demo.
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.
You can use
ex.GetMessage()
Thanks
Got this from one of my teachers. Might be helpful for other beginners like me.
(This is not a part of any h.w./assignment/etc. Curiosity.)
public class ExceptionDemo{
public static void main(String[] args){
int[] array = new int[2];
try {
System.out.println(array[100]);//non-existent
} catch (IndexOutOfBoundsException ex){
StackTraceElement[] e = ex.getStackTrace();
System.err.println("Got error= " + ex + "\n"+
"in file "+e[0].getFileName() +"\n"+
"in class "+e[0].getClassName() +"\n"+
"in method "+e[0].getMethodName() +"\n"+
"in line "+e[0].getLineNumber());
System.err.println("Full trace= ");
ex.printStackTrace(System.err);
}
System.out.println("As Salamu Alaikum");
}
}
import java.io.FileNotFoundException;
import java.util.Formatter;
import java.util.FormatterClosedException;
import java.util.NoSuchElementException;
import java.util.Scanner;
public class CreateTextFile
{
private Formatter formatter;
public void openFile()
{
try
{
formatter = new Formatter("clients.txt");
}
catch (SecurityException securityException)
{
System.err.println("You do not have permission to access this file");
System.exit(1);
}
catch (FileNotFoundException fileNotFoundException)
{
System.err.println("Error opening or creating the file");
System.exit(1);
}
}
public void addRecords()
{
AccountRecord accountRecord = new AccountRecord();
Scanner scanner = new Scanner(System.in);
System.out.printf("%s%n%s%n%s%n%s%n", "To terminate input, type the end-of-file indicator", "when you are prompted to enter input", "On Unix/Linux/Mac OS X type <control> d then press Enter", "On Windows type <ctrl> z then press Enter");
while (scanner.hasNext())
{
try
{
accountRecord.setAccountNumber(scanner.nextInt());
accountRecord.setFirstName(scanner.next());
accountRecord.setLastName(scanner.next());
accountRecord.setBalance(scanner.nextDouble());
if (accountRecord.getAccountNumber() > 0)
formatter.format("%d %s %s %,.2f%n", accountRecord.getAccountNumber(), accountRecord.getFirstName(), accountRecord.getLastName(), accountRecord.getBalance());
else
System.out.println("Account number must be greater than 0");
}
catch (FormatterClosedException formatterClosedException)
{
System.err.println("Error writing to file");
return;
}
catch (NoSuchElementException noSuchElementException)
{
System.err.println("Invalid input. Try again");
scanner.nextLine();
}
System.out.printf("%s %s%n%s", "Enter account number (>0),", "first name, last name and balance.", "?");
}
scanner.close();
}
public void closeFile()
{
if (formatter != null)
formatter.close();
}
}
I was just wondering why in openFile() the catch blocks are terminated with System.exit() and the catch blocks in addRecords() terminate with return. Is there a recommended way of when each should be used?
They do different things. return simply returns from the function to its caller and the program continues running. System.exit() terminates the program; control does not return to the caller.
You should use System.exit() when your program encounters an unrecoverable error and there is no point in the program continuing to run. Use return when your program can gracefully recover, or when the program should perform cleanup/closeout actions before exiting.
See also this more extended discussion of System.exit().
The return should have been a break, just leaving the while-loop, so that scanner.close() is done.
System.exit is bad style, but feasible for a command line program. Not catching the exception would be somewhat the same: termination with a message, but then with a stack trace too.
In this letting the function throw an exception would be the preferable way.
return statement is used inside a method to come out of it.System.exit(0) is used in any method to come out of program.
System.exit(0) terminates the program narmally.Whereas System.exit(1) terminates the program because of some error encountered in the program.
System.exit() terminates the program at the line of invocation.
System.exit(1) terminates the program if an error occurs.
I have done so much analysis on how sonar cpd detects duplicate blocks.But I am not able to trigger out exactly what the process it takes to detect blocks or lines of code.Do that have any minimum number of lines.
For example if I am writing as below it is not detecting any code duplications even I repeat more that 20 times.
System.out.println("this is good");
System.out.println("this is good");
System.out.println("this is good");
System.out.println("this is good");
System.out.println("this is good");
System.out.println("this is good");
System.out.println("this is good");
System.out.println("this is good");
System.out.println("this is good");
System.out.println("this is good");
Later on I tried giving blocks duplications
try
{
connection = null;
}
catch(Exception e){
e.printStackTrace();
}
try
{
connection = null;
}
catch(Exception e){
e.printStackTrace();
}
try{
connection = null;
}
catch(Exception e){
e.printStackTrace();
}
try{
connection = null;
}
catch(Exception e){
e.printStackTrace();
}
Here it is considering as two block even though it has many blocks.
Please let me know the exact process followed in this duplication detection by sonar 3.4.1
In this
http://docs.sonarsource.org/3.1/apidocs/src-html/org/sonar/plugins/cpd/SonarEngine.html
I found a constant block size as 10. But I am able to relate this in my observation.
A block is the lines of code between balanced braces. The constant block size means that in the block there must be 10 Lines of code to match. So to have a duplication try this.
public void foo(){
//... 10 lines of code
}
private void bar(){
//.... the same 10 lines of code
}
There are a few similar questions, but for C# mostly.
#Override
public void setExtraItemsDone(XMPPResourceConnection session) throws NotAuthorizedException
{
try
{
cp1 = Calendar.getInstance().getTimeInMillis();
try
{
...
} catch (TigaseDBException e) {
...
} catch (UnsupportedOperationException e) {
...
}
} catch (Exception e) {
cp2 = Calendar.getInstance().getTimeInMillis();
throw new NotAuthorizedException(e.getMessage() + "; method took " + (cp2 - cp1) + " ms", e);
}
I am basically looking to catch a MySQLTimeoutException and turn it into a NotAuthorizedException (while keeping an eye for any other stuff besides TigaseDBException and UnsupportedOperationException) in the last catch block. Somehow, java eludes my master plan.
Logs show a straight
com.mysql.jdbc.exceptions.MySQLTimeoutException: Statement cancelled due to timeout or client request
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1754)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2019)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1937)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1922)
at tigase.db.jdbc.JDBCRepository.addDataList(JDBCRepository.java:183)
at tigase.db.jdbc.JDBCRepository.setDataList(JDBCRepository.java:1175)
at tigase.db.UserRepositoryMDImpl.setDataList(UserRepositoryMDImpl.java:651)
at tigase.xmpp.RepositoryAccess.setDataList(RepositoryAccess.java:1152)
at tigase.xmpp.RepositoryAccess.setOfflineDataList(RepositoryAccess.java:1204)
**at tigase.xmpp.impl.XGateRoster.setExtraItemsDone(XGateRoster.java:370)**
at tigase.xmpp.impl.DynamicRoster.setExtraItemsDone(DynamicRoster.java:377)
at tigase.xmpp.impl.JabberIqRoster.dynamicSetRequest(JabberIqRoster.java:178)
at tigase.xmpp.impl.JabberIqRoster.process(JabberIqRoster.java:329)
at tigase.server.xmppsession.SessionManager$ProcessorWorkerThread.process(SessionManager.java:2135)
at tigase.util.WorkerThread.run(WorkerThread.java:132)
As far as i can tell, the bolded line in the stack trace should have changed the exception to a NotAuthorizedException breed. What am I missing ?
Thanks
I agree. the problem is not with the code as posted. Check your assumptions. Are there other overloadings of XGateRoster.setExtraItemsDone? Try using Jad to decompile the class file you are running against. If you enable the options to show line numbers, you can be sure the (decompiled) source you are viewing is exactly the code that is executing. Do you know exactly where the log message you are looking at comes from? Maybe it comes from higher up the stack, after it is thrown but before this catch block and exception translation code are even hit.