Exception handling not triggered/unexpected behaviour in program - java

I have a java program that takes command line arguments and then converts the decimal value to its hexadecimal counterpart. I am trying to make use of an exception handling code block (try/catch) which is not being triggered. The try/catch block is intended to be triggered when no command line arguments are passed to the program.
Have ran program through Jenkins/SonarQube to identify code smells and remedy issues. Have utilised process of trial and error, to experiment with different possibilities to see if I can resolve the design flaw.
https://pastebin.com/frBq46zs
//import java.util.Scanner;
public class Dec2Hex
{
public static int Arg1;
public static void main(String args[])
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter any number: ");
//Arg1= scan.nextInt();
//scan.close();
if (args.length < 0)
{
try
{
Arg1 = Integer.parseInt(args[0]);
}
catch (NumberFormatException e)
{
System.err.println("Argument" + args[0] + " must be an integer.");
System.exit(1);
}
}
Utilising if (args.length > 0) with no command line value results in the exception not being triggered. I thought that this was to be expected, because the exception block would never be triggered because the conditional statement has not been satisfied.
However, the converse was not as expected. I thought that if (args.length==0) then this would mean "no arguments have been passed, attempt to parse the value entered, at the command line. If still despite that, no value can be parsed, THEN trigger the catch statement generating the error message and output it to the user."
Whenever I use args.length==0 or args.length<0 with no command line arguments submitted, all I get is a:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0
Message which specifically refers to the following line of code:
Arg1 = Integer.parseInt(args[0]);

In your code Arg1 = Integer.parseInt(args[0]); before method call Integer.parseInt method arguments will be resolved. So it will try to get first element from argument list (as Java array is 0 based it will get first element with index 0).
As you are not passing any command line argument, code is breaking during argument resolution. Because the array length is 0, args[0] is giving ArrayIndexOutOfBoundsException. Which is an expected scenario. So you should case this exception as well.
try
{
Arg1 = Integer.parseInt(args[0]);
}
catch (ArrayIndexOutOfBoundsException e)
{
System.err.println("No Argument Provided.");
System.exit(1);
}
catch (NumberFormatException e)
{
System.err.println("Argument" + args[0] + " must be an integer.");
System.exit(1);
}
And you don't need that if condition of checking for argument length, if you want to execute the exception code for 0 length. If you want to execute existing exception block pass argument that is not a number and remove the if condition.
In summary, code will reach to NumberFormatException block when you pass some argument and that is not a number. And that exception will be thrown by Integer.parseInt. And current exception is being thrown by args[0] because array length is 0 and you are trying to retrieve the first array element from empty array and it's throwing ArrayIndexOutOfBoundsException.
Although it's not desirable to reach to exception code, while you can handle that even before that.

Related

Java Pre assign args before passing from command line

I am developing a very simple Java application, through which to take files from a folder, obtain information from them and save them in the database.
The app is launched from the command line, and I need to pass the following parameters: file_path, db_name, db_user, db_host, db_user_psw.
When I run the check to see if all the parameters have been passed, in case a parameter is missing, I get an index out of bound exception, correctly according to java.
My need is to bypass this exception and display a string indicating an error message.
For example, if all parameters except db_user_psw are entered, instead of getting index of bound exception I would like the message "You must enter the password to access the db!".
My idea is to pre-assign the args to null, and once the script is run check if they are null or not.
Is it possible to do this in java? I accept any advice or suggestion
My code:
if(args[0] == null ){ System.out.println("Insert a valid Path!"); System.exit(0); }
if(args[1] == null ){ System.out.println("Insert the DB IP!"); System.exit(0);}
if(args[2] == null ){ System.out.println("Insert a DB name!"); System.exit(0);}
if(args[3] == null ){ System.out.println("Insert a DB Username!"); System.exit(0);}
if(args[4] == null ){ System.out.println("Insert User DB Password!"); System.exit(0);}
When I run the check to see if all the parameters have been passed, in case a parameter is missing, I get an index out of bound exception, correctly according to java. My need is to bypass this exception and display a string indicating an error message.
Check the length of args instead:
if(args.length == 0){ System.out.println("Insert a valid Path!"); System.exit(0); }
if(args.length == 1){ System.out.println("Insert the DB IP!"); System.exit(0);}
// ...
(You should exit with a non-zero code, in order to indicate an error)
I think you should really consider using named flags, so your command line isn't just a "meaningless" sequence of arguments that can easily be put in the wrong order. So rather than
java YourMainClass whatever blah etc
you provide something like:
java YourMainClass --file_path=whatever --db_name=blah etc
For your specific question of "Is it possible to do this in java?": You can, by copying the args array:
if (args.length < 5) args = Arrays.copyOf(args, 5);
// or
args = Arrays.copyOf(args, Math.max(5, args.length));
If args has fewer than 5 elements, this will create an array with 5 elements, padding the "missing" elements with null.
But this is an odd and unnecessary thing to do: checking the length is easier.
I am not entirely sure on this, since I am a beginner myself but did you consider to wrap it into a try - catch block?
try {
// Your logic to execute
}
catch(Exception e) {
System.out.println("Insert User DB Password! " + e);
// or something else
}```

taking even number from user and giving exception error if number is odd

I am a java student and I am writing a java program with exception handling. In this program, I am trying to write a program that gets 5 even number from user and if the user enter odd number then show an exception that the number is odd. I am using custom exception "oddexception" in this program.
Now let's talk about the issue. So I have an issue that this program isn't compiling. It show an error which is mentioned in the image below.
The answer to this question can be small and stupid for you but I am a beginner in java so this answer really matters for me. please help me.
Please help me to find a solution. The solution
import java.lang.Exception;
class oddexception extends Exception
{
oddexception(String message, int a)
{
System.out.println(message);
System.out.println("Invalid Number is/are "+a);
}
}
class program4
{
public static void main(String args[])
{
Integer n[] = new Integer[5];
int j=0;
for(int i=0; i<5; i++)
{
try
{
n[i] = Integer.valueOf(args[i]);
if(n[i]%2!=0)
{
j++;
throw new oddexception("Number is odd "+n[i]);
}
}
catch(oddexception e)
{
System.out.println("Caught my exception");
}
}
System.out.println("Invalid numbers are : "+j);
}
}
From the error message it quite clear that the constructor of your exception is expecting a String and an integer (oddexception(String message, int a)). Where as you just passing a String.
throw new oddexception("Number is odd "+n[i]); //results to String
So changing a bit of your code
throw new oddexception("Number is odd " , n[i]);
Your oddexception constructor has two arguments, so instead of
throw new oddexception("Number is odd "+n[i]);
you should write
throw new oddexception("Number is odd ",n[i]);
First of all, I wanted to ask to you follow Java coding convention and start your ClassNames with an uppercase character and then follow camel casing, by following these conventions your code will become more readable and understandable.
Now about your problem, you are accepting two arguments in your constructor oddexception(String message, int a), one String and one int.
But while calling it you are passing only one argument "Number is odd "+n[i], because n[i] will concatenate with the String and become a String.
So instead of throw new oddexception("Number is odd "+n[i]); you should write throw new oddexception("Number is odd ", n[i]);

JAVA - logic error in main method

I have an assignment that requires me to write a program in JAVA with 10 different methods including the main. It obtains the input from a file in order to extract data from a second file through the various methods. Lastly it prints the results to a third file. THis is an intro class and we were insturcted to use the hasNext method. THe second file where the data is retrieved from has 10 rows and 5 columns, each column representing something different. I used sc1.nextInt() since our professor warned us that the programs will read every piece of data and we havent learned how to extract data from just one column. I am stuck on an error I keep receiving. I have included a snippet of my code if anyone can help me. Thank you.
this is the error I keep receiving:
Exception in thread "main"
java.util.InputMismatchException at
java.util.Scanner.throwFor(Scanner.java:864) at
java.util.Scanner.next(Scanner.java:1485) at
java.util.Scanner.nextInt(Scanner.java:2117) at
java.util.Scanner.nextInt(Scanner.java:2076) at
homework4.HomeWork4.checkNumber(HomeWork4.java:47) at
homework4.HomeWork4.main(HomeWork4.java:26)
/Users/xiomarahenriquez/Library/Caches/NetBeans/8.2/executor-snippets/run.xml:53:
Java returned: 1 BUILD FAILED (total time: 0 seconds)"
public static PrintStream ps;
public static void main(String[] args) throws Exception {
ps = new PrintStream("elementsResults.txt");
Scanner sc1 = new Scanner(new File("input.txt"));
int atomicNumber, valid=0, invalid=0, totalProcessed=0;
while (sc1.hasNext()) {
atomicNumber = sc1.nextInt();
checkNumber(atomicNumber);
if(checkNumber(atomicNumber)== true){
++valid;
} else {
++invalid;
}
++totalProcessed;
}
}
public static boolean checkNumber (int atomicNumber) throws Exception {
Scanner sc2 = new Scanner (new File("PeriodicTable.txt"));
int columnA = sc2.nextInt();
String columnB;
int columnC,columnD,columnE;
while (sc2.hasNext() && (columnA > -1 || columnA < 118)) {
columnA=sc2.nextInt();
columnB=sc2.next();
columnC=sc2.nextInt();
columnD=sc2.nextInt();
columnE=sc2.nextInt();
if (atomicNumber==columnA) {
return true;
}
}
sc2.close();
return false;
}
I think that the cause of your problem is in the first line of your exception stack trace:
Exception in thread "main" java.util.InputMismatchException
Here's a link to the documentation for the InputMismatchException. I can't say for sure since I don't know what your input files look like but I'm pretty sure that when you're calling nextInt(), the next token read isn't something that can be cast to an int. My guess is that the Scanner is encountering some text or something else preventing it from returning an int. To figure out which token is causing the problem, I'd try wrapping your invocations of nextInt() in try/catch blocks. When the Scanner throws an InputMismatchException, it will not pass the token that caused the exception so that after the exception is thrown you can get the value of the token (like with the next() method) or skip the token altogether. Here's an example (I don't have access to an IDE right now so this isn't tested but hopefully you can get the idea):
//Some initialization code here...
Scanner myScanner = new Scanner(new File("myFile.txt"));
while(myScanner.hasNext()) {
try {
int myIntVariable = myScanner.nextInt();
} catch (InputMismatchException ex) {
System.out.println("Here's the token that caused the problem: " + myScanner.next());
}
}
//The rest of your code here...
By the way, if you're not absolutely sure that the token that you're retrieving is the type that you think it's going to be (in your case an int), it's probably a good idea to wrap that portion of the code in a try/catch block so that you can handle cases where the token isn't what you think it is.
This is my first answer. Hope it helps.
In your while loop you are running the checkNumber method twice. That's unnecessary. Do it just once like below. Also there is a slight difference between ++i and i++ so check this link: what is the difference between i++ & ++i in for loop (Java)?
while (sc1.hasNext()) {
atomicNumber = sc1.nextInt();
if(checkNumber(atomicNumber)== true){
valid++;
} else {
invalid++;
}
totalProcessed++;
}

JVM Exception handling flow of control

Sample code:
package com.company;
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean continueInput = true;
do {
try {
System.out.println("Enter an integer");
int number = input.nextInt();
System.out.println("The number entered is " + number);
continueInput = false;
}
catch (InputMismatchException ex) {
System.out.println("Try again, enter integer only: ");
input.nextLine();
}
}
while (continueInput);
}
}
The above program is to test the InputMismatch exception class. I am not sure at what point the flow of control is passed to the catch block when a letter is entered. Specifically, which scenario happens?
a) The JVM outputs "Enter an integer" and the user types in the letter B. Does the letter B get assigned to the variable number of type int, and then an exception occurs because of this incompatibility OR
b) The JVM outputs "Enter an integer" and the user types in the letter B. Does the input get checked first to determine if it is an Integer and if not throw an exception to transfer control to the catch block?
or
C) None of the above?
I think it is a bit of B and C.
nextInt() is defined as returning an int. So it has to check the input and convert it to an int. If it can't make an int out of it, it can't just return any old thing (like a letter or a String), because it can only return int.
In that case, it doesn't return at all. It throws an exception. The statement that called nextInt() is abandoned; nothing else happens in that statement. In Java terminology, it completes abruptly. If there were other methods that the statement was going to call, they don't get called. If there was an assignment that the statement was going to perform, it doesn't happen. That's how exceptions work.
And any statement after that statement doesn't get executed, either--they just get skipped.
In this case, the statement
int number = input.nextInt();
gets completed abruptly. Since it's in a try block, though, the program then sees if there's a catch block for the exception. In this case, there is. So after the above statement gets completed abruptly, the program jumps over everything else to the first statement in the catch block.
If there were no try block, however, the whole method would be completed abruptly. Then the statement that called that method would also complete abruptly, which could cause the method that it's in to complete abruptly, and so on until it's either caught or causes your program to crash with a stack trace.
Please try the Oracle tutorials on exceptions (https://docs.oracle.com/javase/tutorial/essential/exceptions/handling.html) for more information on how exceptions work.

Why does my Java program exit after an exception is caught?

I am trying to figure out how to continue a code even after an exception is caught. Imagine that I have a text file filled with numbers. I want my program to read all those numbers. Now, lets say there is a letter mixed in there, is it possible for the exception to be caught, and then the code continues the loop? Would I need the Try and catches within a do-while loop? Please provide me with your ideas, I'd greatly appreciate it. I have provided my code just in case:
NewClass newInput = new NewClass();
infile2 = new File("GironEvent.dat");
try(Scanner fin = new Scanner (infile2)){
/** defines new variable linked to .dat file */
while(fin.hasNext())
{
/** inputs first string in line of file to variable inType */
inType2 = fin.next().charAt(0);
/** inputs first int in line of file to variable inAmount */
inAmount2 = fin.nextDouble();
/** calls instance method with two parameters */
newInput.donations(inType2, inAmount2);
/** count ticket increases */
count+=1;
}
fin.close();
}
catch (IllegalArgumentException ex) {
/** prints out error if exception is caught*/
System.out.println("Just caught an illegal argument exception. ");
return;
}
catch (FileNotFoundException e){
/** Outputs error if file cannot be opened. */
System.out.println("Failed to open file " + infile2 );
return;
}
Declare your try-catch block inside your loop, so that loop can continue in case of exception.
In your code, Scanner.nextDouble will throw InputMismatchException if the next token cannot be translated into a valid double value. That is that exception you would want to catch inside your loop.
Yes, I would put your try/catch in your while loop, although I think you'd need to remove your return statement.
Yep. These guys have it right. If you put your try-catch inside the loop, the exception will stay "inside" the loop. But the way you have it now, when an exception is thrown, the exception will "break out" of the loop and keep going until it reaches the try/catch block. Like so:
try while
^
|
while vs try
^ ^
| |
Exception thrown Exception thrown
In your case you want two try/catch blocks: one for opening the file (outside the loop), and another for reading the file (inside the loop).
If you want continue after catching exception:
Remove return statement when you encounter exception.
Catch all possible exceptions inside and outside while loop since your current catch block catches only 2 exceptions. Have a look at possible exceptions with Scanner API.
If you want to continue after any type of exception, catch one more generic Exception . If you want to exit in case of generic Exception, you can put return by catching it.

Categories