Exception cannot be converted to Throwable - java

I'm working on macOS with JDK8.
In catch, I have to give the entire name of exception like
in this case (ArithmeticException e) instead of (Exception e)
to run the code.
If I use (Exception e) it gives an error that I'm not getting on windows os.
why is that??
and how should I solve this??
The code works perfectly on windows OS with JDK8.
On macOS work perfectly if the proper name of the exception (ArithmeticException e) is given.
import java.util.*;
public class ExceptionDemo
{
public static void main(String args[])
{
int a,b,c;
Scanner sc=new Scanner(System.in);
System.out.println("enter first number:");
a=sc.nextInt();
System.out.println("enter second number:");
b=sc.nextInt();
try
{
c=a/b;
System.out.println("Result is:"+c);
}
catch(Exception e)
{
System.out.println("second number cannot be zero/0 "+e);
}
System.out.println("still running");
}
}
This is the error I'm getting as below:
incompatible types: Exception cannot be converted to Throwable
catch(Exception e)

catch(java.lang.Exception e) {
// handle e
}
Use fully-qualified names if you aren't sure what is imported, and what class will be used under the name Exception.
The name Exception looks too broad for your application. [YourApplicationName]Exception would be a cleaner and conflictless root of your exception hierarchy (if you want to have one).

I was having the same problem, but later I noticed that my class name was Exception because of my class name which is(Exception ) I was getting that error .when I changed my class name (filename ) then it work.

If there is any file named "Exception.java" then rename that file and delete that class file then it will work fine.

The problem is your file name is Exception.java and the class you are trying to implement is the same, but from a different package (java.lang.Exception), so either you change your file name, or you can import that package, or you can write the full package at the catch param block.

you should import first
import java.lang.Exception;

Related

Exception in thread "main" java.lang.UnsatisfiedLinkError:proiectP.JavatoC.getval(I)I

This is my code and i have added the .dll to the place where Java_Home is. And i have this error:
Exception in thread "main" java.lang.UnsatisfiedLinkError: proiectP.JavatoC.getval(I)I at proiectP.JavatoC.getval(Native
Method) at proiectP.JavatoC.main(JavatoC.java:19)
public class JavatoC {
public native int getval(int b);
static {
System.loadLibrary("main");
}
public static void main(String[] args) {
try {
int a;
int b=3;
a= new JavatoC().getval(b);
System.out.println(a);
} catch(Exception e) {
System.out.println(e);
}
}
}
I also tried to write a= new proiectP.JavatoC().getval(b) as proiectP is the package. It doesn't work.
It seems library link not done right. There is a problem in the System.loadLibrary. Because it can't show the required method.
These are requirements for using a native code in Java, And I don't know which has not been observed :
First, make sure that the native file is correct, the getval method must be in that dll, exactly with the same specifications of name, input and output.
Second, it is exactly compiled for this use.
The last is in the right direction with the right name.

Error: Editor does not contain a main type

I'm using Jcolibri Studio and everytime I try to rung my CBR application it gives me the error
Error: Does not contain a main type
May currently Main Method(Jcolibri Studio creates this main):
public static void main(String[] args) {
CBRApplication cbrApp = new CBRApplication();
try {
cbrApp.configure();
CBRCaseBase caseBase = cbrApp.preCycle();
for(CBRCase c: caseBase.getCases())
System.out.println(c);
} catch (ExecutionException e) {
e.printStackTrace();
}
}
If I try to Run As > Java Application
It gives me a list of classes and ask me to pick one, but I have no idea which one. Tried almost everything and I keep getting receiving this error.
Not really sure how important it is, but if you go to Project's Properties you can see this little red X (Pretty sure this JRE is installed).

Class Not Found Exception while using class Class

Plz check following code.... class testError has been instantiated but still Class not found exception is generated... If that is true then why statement written in exception handler does not get printed??
class testError
{
void display()
{
System.out.println("This is testError Class");
}
}
class checkResult
{
public static void main(String[] args)
{
testError te = new testError();
te.display();// I hope the class has been created
Class cls = Class.forName("testError"); // will throw ClassNotFound exception
// Why??... Though the class has been
// instantiated
// if we try to put it in trycatch block it will work...Why??
try{ Class cls = Class.forName("testError");}
catch(ClassNotFoundException e)
{
System.out.println("Error found"); //"Error found" will not be printed
// as the class has been instantiated
}
}
}
I can't comment - as my reputation is too low, but your code runs and debugs fine - though I had to alter it a little bit to make it compile:
public static void main(String[] args) throws ClassNotFoundException {
testError te = new testError();
Class<?> cls = Class.forName("testError");
try {
cls = Class.forName("testError");
// If you got there then everything went fine
te.display();
}
catch (ClassNotFoundException e) {
System.out.println("Error found");
}
}
How do you run your code (from the command line, in an IDE)? What is the console output?
You have got to give more helpful information if you want people to investigate your issue.
Finally, Java convention specifies that classes name should begin with an uppercase character (CheckResult and TestError). Also you should avoid using classes in the default package, as those cannot be imported.
First of all Follow java naming convention
Make your main class public
Create some package(not good to create in default packag) like mypackage and put the classes inside them
and try to invoke the method this way
String name = packageName.className.class.getName();//get the name of the class
className o = (className)Class.forName(name)
.newInstance();
//will give an instance of type Object so cast it
o.display();// call the method

NullPointerException when trying to run .jar file

I have just started learning java, and know only a small amount of code, however this is still a simple program. It is more of a prank program, but mostly just to test if I can make a jar file.
Here is the code:
import java.awt.*;
import java.awt.event.*;
import java.lang.*;
import java.util.Random;
public class randommouse {
public static void main(String[] args) {
for (int i=1; i<1000; i++) {
Random rand = new Random();
int w = rand.nextInt(1024) + 1;
int h = rand.nextInt(768) + 1;
int t = rand.nextInt(2000) + 1;
try {
Robot r = new Robot();
r.mouseMove(w,h);
Thread.sleep(t);
} catch (AWTException e) {}
catch (InterruptedException e) {}
catch (NullPointerException e) {}
}
}
}
I save this to file called randommouse.java,
then compile it using
javac randommouse.java
This works and when I run it using
java randommouse
it works fine also.
So then I try to create a jar file. I use the command
jar cvf randommouse.jar randommouse.class
and it works. Afterwards I double click the jar file and it comes up with an error Java Exception.
So then I run it in the cmd with
java -jar randommouse.jar
and get this error
F:\Java>java -jar randommouse.jar
Exception in thread "main" java.lang.NullPointerException
at sun.launcher.LauncherHelper.getMainClassFromJar(LauncherHelper.java:3
99)
at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:463)
F:\Java>
Do I need to put in an argument, and if so where do I put that in and how?
Thank you in advance
Sam
From the JDK doc:
In order for this option to work, the manifest of the JAR file must
contain a line of the form
Main-Class: classname
Here, classname
identifies the class having the public static void main(String[] args)
method that serves as your application's starting point. See the Jar
tool reference page and the Jar trail of the Java Tutorial for
information about working with Jar files and Jar-file manifests.
When you use this option, the JAR file is the source of all user
classes, and other user class path settings are ignored.
You have to set the entry point
$> echo "Main-Class: randommouse" > Manifest
$> jar cfm randommouse.jar Manifest randommouse.class
Did you specify the entry point in the manifest?
http://download.oracle.com/javase/tutorial/deployment/jar/appman.html
A couple of issues with your code that are not related to your actual problem, but are important nevertheless.
1) This statement is unnecessary:
import java.lang.*;
By default, every class in java.lang is implicitly imported. You don't need to do it explicitly.
2) This is dangerously bad code:
try {
// ...
} catch (AWTException e) {
} catch (InterruptedException e) {
} catch (NullPointerException e) {
}
You are catching exceptions that are most likely due to programming errors, and throwing away all evidence that they ever happened. At the very least, you should print out some kind of error message ... and the exception stacktrace to that you can diagnose it.
In this particular context (in a main method), the following is a better approach:
try {
// ...
} catch (Throwable e) {
System.err.println("An unexpected error has occurred:");
e.printStacktrace(System.err);
System.exit(1);
}
I took a look at the source code of the class and it seems to try to get the main class attribute from a list of attributes, which are Strings, and is then invoking the trim() method on the found main class attribute. When the main class is not being specified, there is no main class attribute, which causes the searching method to return null to indicate so, and when trim() is being invoked on it, it is causing the NullPointerException since the searching method has returned null. To avoid this, be sure that the main class is specified in the jar manifest:
[directory of class files]>jar -cvmf [name of manifest] MyApp.jar
And be sure that you have written the manifest right (with the line break at the end):
Main-Class: [name of main class]

Java compiler error: "public type .. must be defined in its own file"?

I am trying to compile this:
public class DNSLookUp {
public static void main(String[] args) {
InetAddress hostAddress;
try {
hostAddress = InetAddress.getByName(args[0]);
System.out.println (hostAddress.getHostAddress());
}
catch (UnknownHostException uhe) {
System.err.println("Unknown host: " + args[0]);
}
}
}
I used javac dns.java, but I am getting a mess of errors:
dns.java:1: error: The public type DNSLookUp must be defined in its own file
public class DNSLookUp {
^^^^^^^^^
dns.java:3: error: InetAddress cannot be resolved to a type
InetAddress hostAddress;
^^^^^^^^^^^
dns.java:6: error: InetAddress cannot be resolved
hostAddress = InetAddress.getByName(args[0]);
^^^^^^^^^^^
dns.java:9: error: UnknownHostException cannot be resolved to a type
catch (UnknownHostException uhe) {
^^^^^^^^^^^^^^^^^^^^
4 problems (4 errors)
I have never compiled/done Java before. I only need this to test my other programs results. Any ideas? I am compiling on a Linux machine.
The file needs to be called DNSLookUp.java and you need to put:
import java.net.InetAddress;
import java.net.UnknownHostException;
At the top of the file
The answers given here are all good, but given the nature of these errors and in the spirit of 'teach a man to fish, etc, etc':
Install IDE of choice (Netbeans is an easy one to start with)
Setup your code as a new project
Click the lightbulb on the line where the error occurs
Select the fix you'd like
Marvel at the power of the tools you have available
Rename the file as DNSLookUp.java and import appropriate classes.
import java.net.InetAddress;
import java.net.UnknownHostException;
public class DNSLookUp {
public static void main(String[] args) {
InetAddress hostAddress;
try {
hostAddress = InetAddress.getByName(args[0]);
System.out.println(hostAddress.getHostAddress());
} catch (UnknownHostException uhe) {
System.err.println("Unknown host: " + args[0]);
}
}
}
You need to import the classes you're using. e.g.:
import java.net.*;
To import all classes from the java.net package.
You also can't have a public class DNSLookUp in a file named dns.java. Looks like it's time for a Java tutorial...
Coming from "The public type <<classname>> must be defined in its own file" error in Eclipse which was marked as duplicate.
I'm thus answering this "duplicate" here:
On Eclipse, you can prepare all your public classes in one file, then right-clic -> Refactor -> Move Type to New File.
That's not exactly the right workaround (this won't let you have multiple public classes in one file at compile time), but that will let you move them around in their proper files when you'll be ready.
Coming from C#, that's an annoying enforced limitation for do-forgettable (tutorial) classes, nonetheless a good habit to have.

Categories