Where's the exception message? - java

I meet a weired problem when I use maven. I execute the following code using "maven exec:java".
Obviously, it should throw a RuntimeException, but I did not see anything in console. But if I execute it in eclipse, I can see the error message. So where does the exception gone ? Thanks
public class HelloWorld {
public static class MyThread extends Thread {
#Override
public void run() {
String str = null;
str = str.trim();
}
}
public static void main(String[] args) throws InterruptedException, IOException {
MyThread thread = new MyThread();
thread.start();
System.in.read();
}
}

Might be a bug of the Maven Exec Plugin (see issues like MEXEC-89 or MEXEC-80). Try with the version 1.2 of the plugin:
mvn org.codehaus.mojo:exec-maven-plugin:1.2:java -Dexec.mainClass="com.acme.Foo"

You could also try adding the -e command line option to your mvn call, I think that solved a similar problem I had.

Related

VS Code still runs Java file even when build fails?

Simple question here. Here is my Java file:
public class Test {
public static void main(String []args) {
System.out.println("It ran!");
}
void a() {
qweifjew;
}
}
When I press "Run" on VS Code, it says build failed do you want to continue? Makes sense since I have compile-time errors. But when I press continue, it is still able to run and display "It ran!". How come?
For more information on the run command:
C:\Users\jeffe\coding-tutorials\learning-jest> cd c:\Users\jeffe\coding-tutorials\learning-jest && c:\Users\jeffe\.vscode\extensions\vscjava.vscode-java-debug-0.27.1\scripts\launcher.bat "C:\Program Files\Java\jdk-11.0.2\bin\java.exe" -Dfile.encoding=UTF-8 -cp C:\Users\jeffe\AppData\Roaming\Code\User\workspaceStorage\5e0a770d0910238b624ead6f98bca1ec\redhat.java\jdt_ws\learning-jest_f8aabfb2\bin Test
It ran!
This is the decompiled .class file of your code:
public class Test {
public Test() {
}
public static void main(String[] args) {
System.out.println("It ran!ddfseffe");
}
void a() {
throw new Error("Unresolved compilation problems: \n\tSyntax error, insert \"VariableDeclarators\" to complete LocalVariableDeclaration\n\tqweifjew cannot be resolved\n");
}
}
You have Auto Save ON in VS code ?
It's able to run a previous successful build to give you an output.

Junit test to fail without failure trace

I'm running JUnit tests from Eclipse, and using the command Assert.fail(message) whenever I want to cause the test to fail. The problem is that I always get the message along with the entire failure trace. Is there any way for JUnit to display the message only, without the stack trace?
Eclipse JUnit settings available via Window --> Preferences --> Java --> Junit allow for cutting stack traces for certain exception classes:
With these settings, the stack trace for the test:
#Test
public void test() {
fail("Not yet implemented");
}
is filtered:
Now try to deselect the "org.junit.*" (or "junit.framework.Assert", depending which version of JUnit you're using), and rerun the test. The stack trace immediately becomes scary:
Perhaps this is the feature you're looking for.
If a test throws an error, the test will normally fail automatically without a message. You could of course catch Exceptions and let the test fail in the catch clause. Something like this:
#Test
public void test() {
try {
// your test
} catch (Exception e) {
fail("I caught an " + e.class.getSimpleName());
}
}
Of course as always when dealing with exceptions, be as precise when catching them as possible.
I found a way to crash the test without showing a long failure trace. Instead of using Assert.fail(), I create my own exception, and set the failure trace to be minimal:
public static void failTest(String message) throws MyTestFailure {
System.err.println(message);
MyTestFailure exception = new MyTestFailure(message);
StackTraceElement elem = new StackTraceElement("com.my.package.Utils", "failTest", "failTest", 3);
StackTraceElement elem1[] = new StackTraceElement[1];
elem1[0] = elem;
exception.setStackTrace(elem1);
throw exception;
}
and this way I only print the message that I want to print, and a single line after that
I would simply override the printStackTrace()-methods for my custom Throwable:
Exception -> ERROR
AssertionError -> FAILURE
import java.io.PrintStream;
import java.io.PrintWriter;
public class TestErrorException extends Exception{
private static final long serialVersionUID = -3486394019411535690L;
private String message;
public TestErrorException(String message) {
this.message = message;
}
#Override
public void printStackTrace() {
System.err.println(message);
}
#Override
public void printStackTrace(PrintStream s) {
s.println(message);
}
#Override
public void printStackTrace(PrintWriter s) {
s.println(message);
}
}

Java Class.forName method java.lang.ClassNotFoundException;

I've found other thread where people had and solved this error; however, all of were NOT using fully qualified class paths. I cannot seem to get Class.forName to work and I am using fully qualified paths.
I've tested compiling from CLI and using ItelliJ Idea. Both fail with the same error.
Code (in test directory):
package test;
public class Test {
public static void main(String[] args) {
Class cls = Class.forName("java.util.ArrayList");
}
}
Error:
java.lang.ClassNotFoundException; must be caught or declared to be thrown
The example above does NOT work. Thanks in advance!
You're getting this message because ClassNotFoundException is a checked exception. This means that this exception can not be ignored. You need to either surround it with a try/catch construct and provide exception handling or add a throws clause to your method and handle it in a callee.
EDIT:
Please note that Class.forName() construct is not resolved during compilation. When you write such a statement, you're telling the JVM to look during program execution for a class which may not have been loaded. Java libraries are dynamically linked instead of statically linked, meaning that their code is not incorporated in your program code, being loaded only when requested. This is why it throws ClassNotFoundException.
Class.forName("java.util.ArrayList") method declared to throw a checked exception ClassNotFoundException, so you must handle it inside a try/catch block like following
package test;
public class Test {
public static void main(String[] args) {
try {
Class cls = Class.forName("java.util.ArrayList");
} catch (ClassNotFoundException e) {
// Handle it here
}
}
}
Try this:
try{
Class cls = Class.forName("java.util.ArrayList");
}catch(ClassNotFoundException e){
... do messaging or logging
}
or throw ClassNotFoundException in the methods signature:
public static void main(String[] args) throws ClassNotFoundException {
I don't know why none of the answers above can explain why this error happened. Neither can I, but I once encountered this issue and solved it by using
Thread.currentThread().getContextClassLoader().loadClass($YOUR_CLASS_NAME)
Hope it can solve your problem and hope someone can give us an explanation.
There are two options:
Surround with a try-catch block and do some appropriate handling:
package test;
public class Test {
public static void main(String[] args) {
try {
Class cls = Class.forName("java.util.ArrayList");
} catch(ClassNotFoundException e) {
System.out.println("This is not a very serious exception, or at least Test knows how to handle it");
}
}
}
Throw it outside the method in the hope that some calling method will know what to do.
package test;
public class Test {
public static void main(String[] args) throws ClassNotFoundException {
Class cls = Class.forName("java.util.ArrayList");
}
}

When I run the following code, it throws an Exception, why?

code:
public class JniTest {
static {
System.load("/usr/lib/libJniTest.so"); //It run have no exception and true
//System.loadLibrary("libJniTest");
}
public native void sayHello();
public static void main(String[] args) {
System.out.println(System.getProperties().getProperty("java.library.path"));
new JniTest().sayHello();
}
}
If use the comments code instead of "System.load("/usr/lib/libJniTest.so"), it will throw exception:
Exception in thread "main" java.lang.UnsatisfiedLinkError: no libJniTest in java.library.path!
I have input
export LD_LIBRARY_PATH=/usr/lib in /etc/profile and set vm arguments:
-Djava.library.path=/usr/lib
Help me, Please!
Set VM arguments with :
-Djava.library.path="${workspace_loc}/project_name:${env_var:PATH}"
and make sure that .so should be in your project folder

Java threads problem

I have a problem with java threads:
public class MyClass{
public void Core(){
runTools(); //here I would like to call runTools() method
}
public void runTools(){
final String run_tool ="cmd.exe /C sources.exe";
Runnable doRun = new Runnable() {
public void run() {
try {
Process tool_proc = Runtime.getRuntime().exec(run_tool);
}
catch (IOException e) {
e.printStackTrace();
}
}
};
Thread th = new Thread(doRun);
th.start();
}
}
If I do this, then I don't know why, but the thread doesn't work. Please give me some ideas to create a thread. I have already been seen lots of examples, but I should some code such as my example here. Thanks!
At first, if you just want to execute an external command and do not bother about its output*, then using a dedicated thread is unnecessary, since the process itself will already run in parallel to your application, so the exec() call will not really hang your programm.
Nevertheless your code looks correct to me. You should check the working directory of your application (maybe cmd.exe cannot find your sources.exe) and evaluate the output the process you start gives you, by directing the streams of tool_proc.getErrorStream() and tool_proc.getInputStream() to System.out or logging them.
EDIT:
* The Java documentation states you always should read the InputStreams of your processes as failing to do so might result in filling up a system buffer, which will eventually hang the process.
problem 1 You create object for Runnable Interface,that is never possible.
Runnable *obj=new Runnable(); // this is not correct
problem 2 You write definition for Run() method with in the another method runTools()
we can create object for a class that implements The Runnable interface.
Due to these your code is not working.
Try the fallowing way
public class MyClassName1 implements Runnable
{
public void start()
{
//here you can call your method:runTools()
runTool();
}
}
public void runTools()
{
final String run_tool ="cmd.exe /C sources.exe";
try
{
Process tool_proc = Runtime.getRuntime().exec(run_tool);
}
catch (IOException e)
{
e.printStackTrace();
}
}
here is my main class of the programe
public class MyClassName2
{
public static void main(String[] ars)
{
Runnable *obj1=new MyClassName1();
Thread t=new Thread(obj);
t.start()
}
I hope this helps to you

Categories