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
}
Related
I want to find out the error line number using try and catch. I tried to get some information from How to get error line number of code using try-catch, but it didn't help since I use different language.
Now, I am getting java.lang.NumberFormatException: For input string: "" when I do
try {
// My Code Here
} catch(Exception e) {
System.out.println(e);
}
I tried printing e.getStackTrace()[0].getLineNumber()); as well, but it seems like it's not showing the correct error line number. Is there any way I can get it easily? I have a pretty big file and I don't think I'll be able to go over line by line to figure out what's wrong.
Thanks!
If you use a Logger library, it can print the stack trace in debug mode that points to the line number. else printStackTrace() is your friend.
try {
// My Code Here
} catch(Exception e) {
System.out.println(e);
e.printStackTrace(); // This will give line number
}
package com.ms.common;
public class Run {
public static void main(String[] args) {
try {
int value = 5;
int divider = 0;
int result = value / divider;
} catch (Exception e) {
System.out.println(e.getStackTrace()[0]);
}
}
}
Error at Run.java at line# 11
com.ms.common.Run.main(Run.java:11)
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");
}
}
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);
}
}
I put the declaration in the while loop, and the program would not running and also does not return any error. I suspect the while loop become an infinite loop.
try
{
while (true)
{
inputStream = new ObjectInputStream (new FileInputStream (fileName));
Ship copyObject = (Ship) inputStream.readObject();
String nameCompany = copyObject.getCompanyName();
if (compName.equalsIgnoreCase(nameCompany)){
listShipName += (copyObject.getShipName() + ", ");
numberOfShip ++;
}
}
}
catch (EOFException e)
{
}
catch (Exception e)
{
e.printStackTrace();
}
But if I put the declaration of input stream out of the while loop, the program runs successfully. Can someone explain why this happens?
try
{
inputStream = new ObjectInputStream (new FileInputStream (fileName));
}
catch (Exception e)
{
e.printStackTrace();
}
try
{
while (true)
{
Ship copyObject = (Ship) inputStream.readObject();
String nameCompany = copyObject.getCompanyName();
if (compName.equalsIgnoreCase(nameCompany)){
listShipName += (copyObject.getShipName() + ", ");
numberOfShip ++;
}
}
}
catch (EOFException e)
{
}
catch (Exception e)
{
e.printStackTrace();
}
You're reopening your file on every iteration through the loop, which means you are only ever reading the first object from the file. But you're reading the same object over and over again.
As well as opening your file only once, you really should try to detect the end of file without throwing an exception. As a matter of style, exceptions should be thrown when things go wrong, not as a matter of course.
Now I realize that in each iteration, I reopen the input stream, so the loop would not reach to the end of the file, and it becomes infinite.
I have these 2 methods to read a number of integers from a file and insert them in a tree. It works fine if the file is found but if the file is not found it doesn't print "File not found". Why is it not going into the catch statement? Thanks!
public static void openF(Tree myT)
{
try
{
x=new Scanner(new File("Number.txt"));
readF(myT);
}
catch(Exception e)
{
System.out.println("File not found");
}
}
// to read from the file
public static void readF(Tree myT)
{
while(x.hasNext()) //keeps going till it reaches the end of file
{
int a =x.nextInt();
myT.insert(a); //insert in tree
}
}
I tested a simplified version of your code:
public static void main(String[] args) {
try {
new Scanner(new File("H:\\Hello.txt"));
System.out.println("The file exists.");
} catch (Exception e) {
System.out.println("File not found: " + e.getMessage());
}
}
When the file exists, it prints The file exists.. If not, it prints File not found: H:\Hello.txt (The system cannot find the file specified).
So no, the catch block is running as expected. The error is somewhere else in your code, but given that you're not providing the full code, nor a part which actually compiles (x is not declared), there is no way for us to guess where the actual error is.