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());
}
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();
}
}
I have no idea why I am getting this error, In the program i am not accessing any array. But its still giving this error.
java.lang.ArrayIndexOutOfBoundsException: 0
at oracle.jdbc.driver.OracleSql.main(OracleSql.java:1666)
I have posted the code below.
public class ItT4 {
public static void main(String[] args) {
try {
// loading the class
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (Exception e) {
e.printStackTrace();
}
}//closing main
}//closing class
I have set the class path required for drivers. and even gone through few links in stackoverflow.
Modified
I removed everything and tried printing out the s simple statement. Still i am getting the same error. The code is given below.
public class ItT4 {
public static void main(String[] args) {
System.out.println("hello boss");
}
}
you can follow the following process
click project
click on clean
select your project
Okay for a class I had to build a queue ADT and use that ADT to create an application that does basic adding/subtracting. The problem is that when I try to invoke the queue's methods that have an exception linked to them I get " error: unreported exception FullCollectionException; must be caught or declared to be thrown".
Here is what my code looks like.
public void insert(Object element) throws FullCollectionException
{
if(isFull())
throw new FullCollectionException("Queue");
else
{
queue[count] = element;
count++;
}
}
The isFull method just does a simple comparison to see if the array has met its length. Then the class that uses it is as follows.
public class Stocks
{
public static void main(String a[])
{
Queue q = new Queue();
StackObject so = new StackObject();
q.insert(10);
q.insert(30);
}
}
I tried several different things but none seemed to work.
Unless FullCollectionException is a child of RuntimeException (which is unchecked), you won't be able to do that. Try this:
try {
q.insert(10);
q.insert(30);
} catch (FullCollectionException fce) {
// Handle exception
}
You need to declare that main() could potentially throw that exception, like this:
public static void main(String a[]) throws FullCollectionException
{
Queue q = new Queue();
StackObject so = new StackObject();
q.insert(10);
q.insert(30);
}
Or you could add a catch block instead, but you should only ever do that if you have an actual plan to recover from the exception. Otherwise, it's actually better to let your program fail rather than silently sweep problems under the rug.
You need to explicitly throw or catch the FullCollectionException in the main method.
PS: if you use an IDE such as Eclipse or Netbeans to write your code, you will be prompted to add such exception handling statements.
Figured it out. I made the exceptions as part of my assignment and I just had them be a child of Exception instead of RuntimeException. Thanks for all your help :))
Is it possible to construct a snippet of code in Java that would make a hypothetical java.lang.ChuckNorrisException uncatchable?
Thoughts that came to mind are using for example interceptors or aspect-oriented programming.
I haven't tried this, so I don't know if the JVM would restrict something like this, but maybe you could compile code which throws ChuckNorrisException, but at runtime provide a class definition of ChuckNorrisException which does not extend Throwable.
UPDATE:
It doesn't work. It generates a verifier error:
Exception in thread "main" java.lang.VerifyError: (class: TestThrow, method: ma\
in signature: ([Ljava/lang/String;)V) Can only throw Throwable objects
Could not find the main class: TestThrow. Program will exit.
UPDATE 2:
Actually, you can get this to work if you disable the byte code verifier! (-Xverify:none)
UPDATE 3:
For those following from home, here is the full script:
Create the following classes:
public class ChuckNorrisException
extends RuntimeException // <- Comment out this line on second compilation
{
public ChuckNorrisException() { }
}
public class TestVillain {
public static void main(String[] args) {
try {
throw new ChuckNorrisException();
}
catch(Throwable t) {
System.out.println("Gotcha!");
}
finally {
System.out.println("The end.");
}
}
}
Compile classes:
javac -cp . TestVillain.java ChuckNorrisException.java
Run:
java -cp . TestVillain
Gotcha!
The end.
Comment out "extends RuntimeException" and recompile ChuckNorrisException.java only :
javac -cp . ChuckNorrisException.java
Run:
java -cp . TestVillain
Exception in thread "main" java.lang.VerifyError: (class: TestVillain, method: main signature: ([Ljava/lang/String;)V) Can only throw Throwable objects
Could not find the main class: TestVillain. Program will exit.
Run without verification:
java -Xverify:none -cp . TestVillain
The end.
Exception in thread "main"
After having pondered this, I have successfully created an uncatchable exception. I chose to name it JulesWinnfield, however, rather than Chuck, because it is one mushroom-cloud-laying-mother-exception. Furthermore, it might not be exactly what you had in mind, but it certainly can't be caught. Observe:
public static class JulesWinnfield extends Exception
{
JulesWinnfield()
{
System.err.println("Say 'What' again! I dare you! I double dare you!");
System.exit(25-17); // And you shall know I am the LORD
}
}
public static void main(String[] args)
{
try
{
throw new JulesWinnfield();
}
catch(JulesWinnfield jw)
{
System.out.println("There's a word for that Jules - a bum");
}
}
Et voila! Uncaught exception.
Output:
run:
Say 'What' again! I dare you! I double dare you!
Java Result: 8
BUILD SUCCESSFUL (total time: 0 seconds)
When I have a little more time, I'll see if I can't come up with something else, as well.
Also, check this out:
public static class JulesWinnfield extends Exception
{
JulesWinnfield() throws JulesWinnfield, VincentVega
{
throw new VincentVega();
}
}
public static class VincentVega extends Exception
{
VincentVega() throws JulesWinnfield, VincentVega
{
throw new JulesWinnfield();
}
}
public static void main(String[] args) throws VincentVega
{
try
{
throw new JulesWinnfield();
}
catch(JulesWinnfield jw)
{
}
catch(VincentVega vv)
{
}
}
Causes a stack overflow - again, exceptions remain uncaught.
With such an exception it would obviously be mandatory to use a System.exit(Integer.MIN_VALUE); from the constructor because this is what would happen if you threw such an exception ;)
Any code can catch Throwable. So no, whatever exception you create is going to be a subclass of Throwable and will be subject to being caught.
public class ChuckNorrisException extends Exception {
public ChuckNorrisException() {
System.exit(1);
}
}
(Granted, technically this exception is never actually thrown, but a proper ChuckNorrisException can't be thrown -- it throws you first.)
Any exception you throw has to extend Throwable, so it can be always caught. So answer is no.
If you want to make it difficult to handle, you can override methods getCause(), getMessage(), getStackTrace(), toString() to throw another java.lang.ChuckNorrisException.
My answer is based on #jtahlborn's idea, but it's a fully working Java program, that can be packaged into a JAR file and even deployed to your favorite application server as a part of a web application.
First of all, let's define ChuckNorrisException class so that it doesn't crash JVM from the beginning (Chuck really loves crashing JVMs BTW :)
package chuck;
import java.io.PrintStream;
import java.io.PrintWriter;
public class ChuckNorrisException extends Exception {
public ChuckNorrisException() {
}
#Override
public Throwable getCause() {
return null;
}
#Override
public String getMessage() {
return toString();
}
#Override
public void printStackTrace(PrintWriter s) {
super.printStackTrace(s);
}
#Override
public void printStackTrace(PrintStream s) {
super.printStackTrace(s);
}
}
Now goes Expendables class to construct it:
package chuck;
import javassist.*;
public class Expendables {
private static Class clz;
public static ChuckNorrisException getChuck() {
try {
if (clz == null) {
ClassPool pool = ClassPool.getDefault();
CtClass cc = pool.get("chuck.ChuckNorrisException");
cc.setSuperclass(pool.get("java.lang.Object"));
clz = cc.toClass();
}
return (ChuckNorrisException)clz.newInstance();
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
}
And finally the Main class to kick some butt:
package chuck;
public class Main {
public void roundhouseKick() throws Exception {
throw Expendables.getChuck();
}
public void foo() {
try {
roundhouseKick();
} catch (Throwable ex) {
System.out.println("Caught " + ex.toString());
}
}
public static void main(String[] args) {
try {
System.out.println("before");
new Main().foo();
System.out.println("after");
} finally {
System.out.println("finally");
}
}
}
Compile and run it with following command:
java -Xverify:none -cp .:<path_to_javassist-3.9.0.GA.jar> chuck.Main
You will get following output:
before
finally
No surprise - it's a roundhouse kick after all :)
In the constructor you could start a thread which repeatedly calls originalThread.stop (ChuckNorisException.this)
The thread could catch the exception repeatedly but would keep throwing it until it dies.
No. All exceptions in Java must subclass java.lang.Throwable, and although it may not be good practice, you can catch every type of exception like so:
try {
//Stuff
} catch ( Throwable T ){
//Doesn't matter what it was, I caught it.
}
See the java.lang.Throwable documentation for more information.
If you're trying to avoid checked exceptions (ones that must be explicitly handled) then you will want to subclass Error, or RuntimeException.
Actually the accepted answer is not so nice because Java needs to be run without verification, i.e. the code would not work under normal circumstances.
AspectJ to the rescue for the real solution!
Exception class:
package de.scrum_master.app;
public class ChuckNorrisException extends RuntimeException {
public ChuckNorrisException(String message) {
super(message);
}
}
Aspect:
package de.scrum_master.aspect;
import de.scrum_master.app.ChuckNorrisException;
public aspect ChuckNorrisAspect {
before(ChuckNorrisException chuck) : handler(*) && args(chuck) {
System.out.println("Somebody is trying to catch Chuck Norris - LOL!");
throw chuck;
}
}
Sample application:
package de.scrum_master.app;
public class Application {
public static void main(String[] args) {
catchAllMethod();
}
private static void catchAllMethod() {
try {
exceptionThrowingMethod();
}
catch (Throwable t) {
System.out.println("Gotcha, " + t.getClass().getSimpleName() + "!");
}
}
private static void exceptionThrowingMethod() {
throw new ChuckNorrisException("Catch me if you can!");
}
}
Output:
Somebody is trying to catch Chuck Norris - LOL!
Exception in thread "main" de.scrum_master.app.ChuckNorrisException: Catch me if you can!
at de.scrum_master.app.Application.exceptionThrowingMethod(Application.java:18)
at de.scrum_master.app.Application.catchAllMethod(Application.java:10)
at de.scrum_master.app.Application.main(Application.java:5)
A variant on the theme is the surprising fact that you can throw undeclared checked exceptions from Java code. Since it is not declared in the methods signature, the compiler won't let you catch the exception itself, though you can catch it as java.lang.Exception.
Here's a helper class that lets you throw anything, declared or not:
public class SneakyThrow {
public static RuntimeException sneak(Throwable t) {
throw SneakyThrow.<RuntimeException> throwGivenThrowable(t);
}
private static <T extends Throwable> RuntimeException throwGivenThrowable(Throwable t) throws T {
throw (T) t;
}
}
Now throw SneakyThrow.sneak(new ChuckNorrisException()); does throw a ChuckNorrisException, but the compiler complains in
try {
throw SneakyThrow.sneak(new ChuckNorrisException());
} catch (ChuckNorrisException e) {
}
about catching an exception that is not thrown if ChuckNorrisException is a checked exception.
The only ChuckNorrisExceptions in Java should be OutOfMemoryError and StackOverflowError.
You can actually "catch" them in the means that a catch(OutOfMemoryError ex) will execute in case the exception is thrown, but that block will automatically rethrow the exception to the caller.
I don't think that public class ChuckNorrisError extends Error does the trick but you could give it a try. I found no documentation about extending Error
Is it possible to construct a snippet of code in java that would make a hypothetical java.lang.ChuckNorrisException uncatchable?
Yes, and here's the answer: Design your java.lang.ChuckNorrisException such that it is not an instance of java.lang.Throwable. Why? An unthrowable object is uncatchable by definition because you can never catch something that can never be thrown.
You can keep ChuckNorris internal or private and encapsulate him or swollow him...
try { doChuckAction(); } catch(ChuckNorrisException cne) { /*do something else*/ }
Two fundamental problems with exception handling in Java are that it uses the type of an exception to indicate whether action should be taken based upon it, and that anything which takes action based upon an exception (i.e. "catch"es it) is presumed to resolve the underlying condition. It would be useful to have a means by which an exception object could decide which handlers should execute, and whether the handlers that have executed so far have cleaned things up enough for the present method to satisfy its exit conditions. While this could be used to make "uncatchable" exceptions, two bigger uses would be to (1) make exceptions which will only be considered handled when they're caught by code that actually knows how to deal with them, and (2) allow for sensible handling of exceptions which occur in a finally block (if a FooException during a finally block during the unwinding of a BarException, both exceptions should propagate up the call stack; both should be catchable, but unwinding should continue until both have been caught). Unfortunately, I don't think there would be any way to make existing exception-handling code work that way without breaking things.
It is easily possible to simulate a uncaught exception on the current thread. This will trigger the regular behavior of an uncaught exception, and thus gets the job done semantically. It will, however, not necessarily stop the current thread's execution, as no exception is actually thrown.
Throwable exception = /* ... */;
Thread currentThread = Thread.currentThread();
Thread.UncaughtExceptionHandler uncaughtExceptionHandler =
currentThread.getUncaughtExceptionHandler();
uncaughtExceptionHandler.uncaughtException(currentThread, exception);
// May be reachable, depending on the uncaught exception handler.
This is actually useful in (very rare) situations, for example when proper Error handling is required, but the method is invoked from a framework catching (and discarding) any Throwable.
Call System.exit(1) in the finalize, and just throw a copy of the exception from all the other methods, so that the program will exit.