ClassNotFoundException in isInstance - java

class j {
public static void main(String args[])
{
Object obj=new Object();
String c ="Object";
System.out.println(Class.forName(c).isInstance(obj));
}
}
In the above code i'am trying to find whether obj is an instance of Object or not.I should get the answer as true but i'am getting an error.I am not able to figure out why the error is occurring.Can anyone please help me out?
error: unreported exception ClassNotFoundException; must be caught or
declared to be thrown
System.out.println(Class.forName(c).isInstance(obj));

2 things:
the method forName throws an exception so you need to either catch them or rethrow it.
just doing Class.forName("Object") is not correct, you need to use the fully qualified name of the desired class (i.e with package included)
from the javaDoc
Parameters: className - the fully qualified name of the desired class.
String c = "java.lang.Object";
System.out.println(Class.forName(c).isInstance(obj));

You have to surround the code within try catch or you have to make sure that main can throw excetpion:
try {
System.out.println(Class.forName(c).isInstance(obj));
} catch(ClassNotFoundException ex) {
// do something in case class can not be found
}
or
public static void main(String args[]) throws ClassNotFoundException
You can not leave code, that is able to throw exceptions, without any safety net.
Make sure to use fully qualified name of class:
java.lang.ClassNotFoundException
or import it at the beginning of the source code:
import java.lang.ClassNotFoundException;

The method Class.forName declares that it throws the Exception ClassNotFoundException so in your code you either need to catch it or declare throws ClassNotFoundException in the method declaration. Thus
Public static void main(String[] args) throws ClassNotFoundException {
or
try {
System.out.println(Class.forName(c).isInstance(obj));
} catch (ClassNotFoundException ex) {
System.out.println(ex.getMessage());
}

Related

Unhandled exception type Exception in Eclipse

I have the class Parser in Java like below:
public class Parser {
public ArrayList<MetroStop> listeArrets;
public Parser() {
this.listeArrets = new ArrayList<>();
}
public MetroStop creerArret(String [] parts) {
MetroStop arret = new MetroStop ();
arret.identifiant = Integer.parseInt(parts [0]);
arret.longitude = Double.parseDouble(parts [1]);
arret.latitude = Double.parseDouble(parts [2]);
arret.nom = parts [3];
arret.destination = parts [4];
arret.moyen = parts [5];
return arret;
}
public void parse(String fichier) throws Exception {
try {
Reader reader = new FileReader(fichier);
BufferedReader br = new BufferedReader(reader);
String line;
while((line = br.readLine ()) != null) {
String [] parts = line.split("#");
MetroStop arret = creerArret(parts);
listeArrets.add(arret);
}
br.close();
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
}
}
I also have the Main class:
public class Main {
public static void main(String[] argv) {
Parser teste = new Parser();
teste.parse("ratp_arret.csv");
}
}
When I run the Main class as Java Application i get this error:
"Unhandled exception type Exception", which points to the second line of the main() method.
The file ratp_arret.csv is located in the src folder, which is also the working directory.I am using Eclipse.
I don't understand where this error comes from.
Thank you for your help!
You call teste.parse(someString), where teste is an expression which has type Parser. That means this is a call to the method parse(String) in your Parser type....
and that is declared with throws Exception.
Exceptions are a mechanism to convey alternate return options. The parse method can run its course in one of two ways: It can 'return', in which case it returns nothing (void), or, it can 'throw'. What it can throw is limited by its throws line - in this case, it can throw just about anything (Exception is the supertype of almost all things you can throw).
The way java handles this is that your code needs to handle every possible way a method can conclude.
So, you need a 'path' for your code when the parser() method returns (this is trivial; it's a void method, you get that 'for free', you don't need to write anything special for this), but you also need a path for that other exit scenario: When it throws something. You get handling of RuntimeException for free, but for others, you have two options:
catch it:
try {
teste.parse(someString);
// this code runs in the 'return' case.
} catch (Exception e) {
// this code runs in the 'throws' case.
}
this would imply you know what to do when your parse method decided to exit via the throws path.
Alternatively, you fix this by having your main method also 'fork', and decree that it has two ways to finish: Either via the return route or the throw route:
public static void main(String[] args) throws Exception {
teste.parse(someString);
}
// this main method has declared that it has two separate
// exit routes. 'return', and 'throws something'.
java will start an application by running its main method, and java can deal with a main that has two alternate exit routes (return, or throw something). It handles the 'return' route by doing nothing. It handles the 'throw something' route by printing the type of the exception, the message, the stack trace, and the entire causal chain. That is an excellent default, and you should not attempt to come up with a different one by e.g. catching that exception and attempting to 'log it'.
This: Just add throws Exception to your main method declaration. Put the throws Exception back on your parse method, ignore #Eritrean's advice.
NB: All methods are inherently declared as if they said throws RuntimeException, Error (as in, any error and any runtimeexception can be thrown without writing a throws clause for it, as all methods implicitly have that clause baked in already), this is why I said earlier that RuntimeExceptions are 'handled for free'. The idea is that all exceptions that subclass RuntimeException are things that are so universal or so unlikely, it would be unwieldy to force management of this onto the programmer. That's why you never need to write throws NullPointerException or throws InternalError.
public void parse(String fichier) /*throws Exception*/ {
try {
// ...
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
}
You throw RuntimeException. This is called not-checked exception and it's not mandatory to declare these exeptions in the method declaration and catch it when calle the method.

Catching UnknownHostException which is the cause of an exception

In program of interest, during execution of a method() some HTTP related exceptions can occur. Due to something, that method was set to be able to throw ExpException. My interest is only in specific type of exception, i.e. UnknownHostException, which can be accessed by using
if (e.getCause().getCause().getCause() instanceof UnknownHostException)
which I hope you agree is very nasty way. Thus, this works fine:
public class ExportException extends Exception;
class sth{
method() throws ExpException;
}
class main{
try{
method()
} catch(ExpExceptione e){
if (e.getCause().getCause().getCause() instanceof UnknownHostException){
doSthElse();
}
}
However, I was hoping to do as described below. Unfortunately, Eclipse yells
Unreachable catch block for UnknownHostException. This exception is
never thrown from the try statement.
Is there any help for me? I don't want to use getCause()^3.
An addition: this is a big big project and I'm the new newbie and would rather not mess with outside classes, but just the "main".
My program is something like:
public class ExportException extends Exception;
class sth{
method() throws ExpException;
}
class main{
try{
method()
} catch(UnknownHostException e){
doSth();
} catch(ExpExceptione){
doSthElse();
}
UnknownHostException is a subtype of IOException which is checked exception.
Method that throws checked exceptions must declare them in throws declaration.
Consequently, when you call a method that does not have throws UnknownHostException in declaration, you will never catch this exception - code is unreachable and compiler is correct.
Here you can see how to nicely check if exception cause contains any specific exception.
static boolean hasCause(Throwable e, Class<? extends Throwable> cl) {
return cl.isInstance(e) || e.getCause() != null && hasCause(e.getCause(), cl);
}
catch(ExpException e) {
if (hasCause(e, UnknownHostException.class)) {
doSmth();
} else {
doSmthElse();
}
}

throws keyword in front of main thread

My question is when we use "throws" methodology to throw an exception, why we need to give it in front of main method inspite of already thrown it in respective method which required that like add() method will throw the exception if am using Inputstream reader to take the input, so i used "throws IOException" in front of it and executed the code. But error was coming to handle the IOexception in main thread. So, when i appended "throws IOException" in front of main thread, it executed fine. But i did not get why error was coming in main thread part as add() method was the one to generate the exception and there i handled it.
Please explain this. :)
Code:
class A {
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
public void add() throws IOException {
int a=Integer.parseInt(br.readLine());
int b=Integer.parseInt(br.readLine());
System.out.println("Value after addition : "+(a+b));
}
public static void main(String args[]) throws IOException {
A a=new A(); a.add();
}
}
But i did not get why error was coming in main thread part as add() method was the one to generate the exception and there i handled it.
No, you didn't handle it there. You let it propagate up to the calling method.
Handling an exception means catching it and doing something appropriate:
public static void main(String args[]) {
A a=new A();
try {
a.add();
} catch (IOException e) {
// Don't really know how you want to handle it, so I'll just print a line on System.err.
System.err.println("add() failed!");
}
}
When you use "throws" you don't treat your exception. you just say that you don't want to treat it there and you will treat it in other place (the place you call the method).So throwing it from the method means that you have to treat it from the main or any other place you call your method

what exceptions need to be thrown in java?

I have these two java codes:
class test {
public static void main(String[] args) throws IOException {
System.out.println("Before try”");
try{}
catch(Throwable d ) {}
System.out.println("done");
}
}
it will compile and print Before try and done.
class test {
public static void main(String[] args) throws IOException {
System.out.println("Before try”");
try{}
catch(java.io.IOException e ) {}
System.out.println("done");
}
}
}
this will make compilation error:
exception java.io.IOException is never thrown in body of corresponding
try statement
at javaapplication8.test.main(Try.java:63)
what is the difference between throwable exception and IOException to have these results, Is there a rule to know which exception would need to be thrown or not?
Java has a concept of checked exceptions. All Throwable are checked unless they are a sub-class of Error or RuntimeException
In the catch class, the compiler can work out whether you can throw a checked exception or not (under normal conditions), but it can't tell if you have thrown an unchecked exception so if you catch any unchecked exception, or an parent, it cannot determine whether you might throw it or not.
Your declaration of main promised that it could throw an IOException, but your code broke that promise (because you catch it yourself).

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");
}
}

Categories