Added error handling

This commit is contained in:
Mandeep Moun
2025-10-11 00:21:45 -06:00
parent 8379a326f8
commit 6c591bbf37
2 changed files with 45 additions and 19 deletions

View File

@@ -4,33 +4,56 @@ import japa.parser.ast.body.*;
import japa.parser.ast.visitor.VoidVisitorAdapter; import japa.parser.ast.visitor.VoidVisitorAdapter;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.IOException;
import java.io.File; import java.io.File;
public class LCA_JP1_0_0 { public class LCA_JP1_0_0 {
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
// Checks if file is provided as command line argument
if (args.length == 0) { if (args.length == 0) {
System.out.println("Usage: java LCA_JP1_0_0 <JavaSourceFile>"); System.out.println("Usage: java LCA_JP1_0_0 <JavaSourceFile>");
return; return;
} }
// Makes sure file exits and can be read
File sourFile = new File(args[0]);
if (!sourFile.exists() || !sourFile.isFile() || !sourFile.canRead()) {
System.err.println("Error: File can't be read or it doesn't exist: " + args[0]);
return;
}
try (FileInputStream in = new FileInputStream(sourFile))
// Parse the given Java file // Parse the given Java file
FileInputStream in = new FileInputStream(new File(args[0])); {
CompilationUnit cu = JavaParser.parse(in); CompilationUnit cu;
try {
// Traverse the AST and print local classes cu = JavaParser.parse(in);
new VoidVisitorAdapter<Void>() { } catch (Exception e) {
System.err.println("Error: Failed to parse file");
@Override e.printStackTrace();
public void visit(MethodDeclaration n, Void arg) { return;
super.visit(n, arg);
} }
// Traverse the AST and print local classes
new VoidVisitorAdapter<Void>() {
@Override @Override
public void visit(ClassOrInterfaceDeclaration n, Void arg) { public void visit(MethodDeclaration n, Void arg) {
System.out.println("Found class: " + n.getName()); super.visit(n, arg);
super.visit(n, arg); }
}
}.visit(cu, null); @Override
public void visit(ClassOrInterfaceDeclaration n, Void arg) {
System.out.println("Found class: " + n.getName());
super.visit(n, arg);
}
}.visit(cu, null);
} catch (IOException e) {
System.err.println("Error: Unable to read the file.");
e.printStackTrace();
} catch (Exception e) {
System.err.println("Uneaxpected error occured.");
e.printStackTrace();
}
} }
} }

View File

@@ -1,14 +1,17 @@
public class test { public class test {
void methodOne() { void methodOne() {
class Helper234 { public class Helper234 {
void doStuff() {} void doStuff() {
}
} }
class Helper2 { private class Helper2 {
void doStuff() {} void doStuff() {
}
} }
} }
void methodTwo() { void methodTwo() {
System.out.println("Hello"); System.out.println("Hello");
} }
} }