This code below is the method header and body, but I get the following error: no exception of type object can be thrown an exception type must be a subclass of Throwable. I'm attempting to execute this block of code: catch(Object object).
public void method15665(Class435 class435, int i) {
do {
try {
try {
byte[] is
= new byte[(int) class435.method7563(1085678935)];
int i_3_;
for (int i_4_ = 0; i_4_ < is.length; i_4_ += i_3_) {
i_3_ = class435.method7564(is, i_4_, is.length - i_4_,
(byte) -10);
if (i_3_ == -1)
throw new EOFException();
}
Class224_Sub8 class224_sub8 = new Class224_Sub8(is);
if ((class224_sub8.aByteArray8535.length
- class224_sub8.anInt8536 * 475822179)
< 1) {
try {
class435.method7572(-1683167102);
} catch (Exception exception) {
/* empty */
}
break;
}
int i_5_ = class224_sub8.method13859((short) -7287);
if (i_5_ < 0 || i_5_ > 1) {
try {
class435.method7572(-1683167102);
} catch (Exception exception) {
/* empty */
}
break;
}
if ((class224_sub8.aByteArray8535.length
- class224_sub8.anInt8536 * 475822179)
< 2) {
try {
class435.method7572(-1683167102);
} catch (Exception exception) {
/* empty */
}
break;
}
int i_6_ = class224_sub8.method13737(2071056893);
if ((class224_sub8.aByteArray8535.length
- 475822179 * class224_sub8.anInt8536)
< 6 * i_6_) {
try {
class435.method7572(-1683167102);
} catch (Exception exception) {
/* empty */
}
break;
}
for (int i_7_ = 0; i_7_ < i_6_; i_7_++) {
Class323 class323
= Class399.aClass195_Sub2_Sub1_5932
.method14614(class224_sub8, -2141543778);
if ((Class255.aClass255_3016
== (((Class173_Sub1) this).aClass255Array9960
[class323.anInt5015 * 1568411443]))
&& (Class399.aClass195_Sub2_Sub1_5932.method14624
(class323.anInt5015 * 1568411443, 82620551)
.aClass350_2171.method6687
(-1035085164).aClass5162.isAssignableFrom
(class323.anObject5014.getClass())))
anInterface50_2149.method298((class323.anInt5015
* 1568411443),
class323.anObject5014,
-1250481088);
}
} catch (Exception exception) {
try {
class435.method7572(-1683167102);
} catch (Exception exception_8_) {
exception = exception_8_;
}
break;
}
try {
class435.method7572(-1683167102);
} catch (Exception exception) {
/* empty */
}
} catch (Object object) {
try {
class435.method7572(-1683167102);
} catch (Exception exception) {
/* empty */
}
throw object;
}
} while (false);
}
Does anyone know how fix this? It would be very much appreciated!
replace
} catch (Object object) {
with
} catch (Throwable object) {
actually you don't want to catch Throwable, but probably Exception, RuntimeException or an even more specific class.
You can only catch what can be thrown (IS-A Throwable). Hence, the compiler complains when you try to catch an Object (because it doesn't extend Throwable).
catch (Object o) // Error: Object IS-NOT Throwable
Throwable is inherited by all types of Errors and Exceptions. But, we usually don't catch Errors because a program almost always cannot recover from it for example, an OutOfMemoryError. So, a catch (Throwable t) is not recommended.
When using catch (Exception e) you basically have a catch-all for any exception (checked or un-checked) that might get thrown during the run. To use or not to use a generic catch usually depends on what you're try block is trying to do. For example, when reading a file you would like to handle and respond to a FileNotFoundException differently than say an EOFException.
All exceptions and errors extend Throwable, only those can be thrown and caught.
You can do
try{
throw new Exception();
}catch(Exception e){
// something here
}catch(Throwable t){
// something here
}
When you are writing multiple catch blocks, then keep following points in mind
You cannot write a subclass type AFTER a superclass type. i.e. If you write catch(RuntimeException rt){} AFTER catch(Exception e){} then you will get compiler error that it is already caught.
Related
Consider this question I was asked in an interview
public class Test_finally {
private static int run(int input) {
int result = 0;
try {
result = 3 / input;
} catch (Exception e) {
System.out.println("UnsupportedOperationException");
throw new UnsupportedOperationException("first");
} finally {
System.out.println("finally input=" + input);
if (0 == input) {
System.out.println("ArithmeticException");
throw new ArithmeticException("second");
}
}
System.out.println("end of method");
return result * 2;
}
public static void main(String[] args) {
int output = Test_finally.run(0);
System.out.println(" output=" + output);
}
}
Output of this program throws ArithmeticException not UnsupportedOperationException
Interviewer simply asked how will i let the client know the original exception raised was of type UnsupportedOperationException not ArithmeticException.
I didn't know that
Never return or throw in a finally block. As an interviewer i would expect that answer.
A crappy interviewer looking for a minor technical detail might expect you know Exception.addSuppressed(). You can not actually read the thrown exception in a finally block so you need to store it in the throw block to reuse it.
So something like that:
private static int run(int input) throws Exception {
int result = 0;
Exception thrownException = null;
try {
result = 3 / input;
} catch (Exception e) {
System.out.println("UnsupportedOperationException");
thrownException = new UnsupportedOperationException("first");
throw thrownException;
} finally {
try {
System.out.println("finally input=" + input);
if (0 == input) {
System.out.println("ArithmeticException");
throw new ArithmeticException("second");
}
} catch (Exception e) {
// Depending on what the more important exception is,
// you could also suppress thrownException and always throw e
if (thrownException != null){
thrownException.addSuppressed(e);
} else {
throw e;
}
}
}
System.out.println("end of method");
return result * 2;
}
I would like to know what the exception instance was in this situation:
try {
// some risky actions
} catch (Exception e) {
System.out.println("Get instance name there");
}
How can I achieve this?
Here you go:
try {
throw new ArithmeticException();
} catch (Exception e) {
System.out.println( e.getClass().getCanonicalName());
}
Output:
java.lang.ArithmeticException
The type of the exception is shown as part of the output of:
e.printStackTrace();
To get it programmatically you can use:
String exceptionClassName = e.getClass().getName();
It is poor form to have logic depending on exception sub types within a catch block. Sonar will flag this as a code violation (squid S1193).
Instead you should add multiple catch blocks to catch different types of exceptions:
try {
readFile(fileName);
}
catch (java.io.IOException e) {
LOG.error("Error accessing file {}", fileName, e);
}
catch (java.lang.IllegalArgumentException e) {
LOG.error("Invalid file name {}", fileName, e);
}
Note: Since Log4j 2 (and SLF4J 1.6+) you can add a throwable as the last parameter and it will be recognized as such. So the above will work!
Since Java 7 you can also do a multi-catch:
}
catch (java.io.IOException | java.lang.IllegalArgumentException e) {
LOG.error("Could not read the file {}", fileName, e);
}
The benefit of the multi-catch is that you can handle multiple exception types within a single catch block without having to revert to a common super class (like java.lang.Exception) that would include exception types you didn't want to handle.
Default exception logging is something like
try
{
//
}
catch (Exception e)
{
e.printStackTrace();
}
This will print the stacktrace of the exception to system.err
If you are looking to add some contextual information, you can take a look at Apache Commons ContextedRuntimeException
public static void main(String[] args) {
try {
doSomething();
} catch (ContextedRuntimeException e) {
System.out.println(e.getMessage());
System.out.println(e.getContextEntries());
}
}
private static void doSomething() {
int divisor = 0;
int dividend = 100;
int result;
try {
result = dividend / divisor; // Just throw an exception to test things....
System.out.print("DIVISION RESULT: "+result);
} catch (ArithmeticException e) {
throw new ContextedRuntimeException("Oops..division by zero not allowed", e)
.addContextValue("Divisor", divisor)
.addContextValue("Dividend", dividend);
}
}
would output:
Oops..division by zero not allowed
Exception Context:
[1:Divisor=0]
[2:Dividend=100]
---------------------------------
[(Divisor,0), (Dividend,100)]
The code in the file to test is:
public void testFail() {
assert false;
}
I need to catch this using reflection and increment a "failed" counter. This is my attempt:
try {
Object t = c.newInstance();
m[i].invoke(t, new Object[0]); // m is the array that holds all Methods for c
passed ++;
} catch (AssertionError ae) {
failed ++;
} catch (Exception e) {
errors ++;
}
}
The assertFalse just goes through as passed and does not raise any exceptions. How can I catch this?
Thanks.
I'm working on some server-side code that wraps all exceptions before passing them to the client side, due to this all client facing methods have the following code
try{
DoSomething();
} catch (ExceptionA e) {
throw new CustomException(AType, e);
} catch (ExceptionB e) {
throw new CustomException(BType, e);
} catch (Exception e) {
throw new CustomException(Unexpected, e);
}
to have this repeated in every method seems to violate the DRY principle and I was wondering what the best way to refactor it would be. For instance I was thinking a wrapper method such as:
private void wrapException(Exception e) {
if (e instanceof ExceptionA) {
throw new CustomException(AType, e);
}
etc...
Take a look at AspectJ soften exception.
Also look at Guava's Throwables.
There is also Lamboks sneaky exception.
The other option is to use Anonymous object instances aka closures.
public abstract class Wrapper {
public void execute() {
try {
// do some boiler plate before
this.wrap();
// do some boiler plate after.
} catch (ExceptionA | ExceptionB ex) {
Type t = determineType(ex);
throw new CustomException(t, ex);
}
}
public void abstract wrap();
}
Now in your code you do something like:
new Wrapper() {
public void wrap() {
DoSomething();
}
}.execute()
This is possible in Java7 and up:
http://docs.oracle.com/javase/7/docs/technotes/guides/language/catch-multiple.html
Copy-paste example from above doc:
catch (IOException|SQLException ex) {
logger.log(ex);
throw ex;
}
This is one way to go about it:
Exception caughtEx = null;
String extraInfo = null;
try{
DoSomething();
} catch (ExceptionA e) {
caughtEx = e;
extraInfo = AType;
} catch (ExceptionB e) {
caughtEx = e;
extraInfo = BType;
} catch (Exception e) { // catching Exception is usually a bad idea, just let it bubble up without catching...
caughtEx = e;
extraInfo = Unexpected;
}
if (caughtEx != null) throw new CustomException(extraInfo, caughtEx);
What's better between several ChildException catch blocks and one Exception catch block? By better, I mean in a good-practices way.
To illustrate:
public static void main(String[] args) {
System.out.println(Main.isNonsense1(null)); // false <- bad
System.out.println(Main.isNonsense2(null)); // NullPointerException <- good
}
// More readable, less precise
public static boolean isNonsense1(String className) {
try {
Class.forName(className);
String.class.getConstructor(String.class);
className.getBytes("UTF-8");
MessageDigest.getInstance("SHA-1").wait();
return true;
} catch (Exception e) {
return false;
}
}
// Less readable, more precise
public static boolean isNonsense2(String className) {
try {
Class.forName(className);
String.class.getConstructor(String.class);
className.getBytes("UTF-8");
MessageDigest.getInstance("SHA-1").wait();
return true;
} catch (ClassNotFoundException e) {
return false;
} catch (NoSuchMethodException e) {
return false;
} catch (SecurityException e) {
return false;
} catch (UnsupportedEncodingException e) {
return false;
} catch (NoSuchAlgorithmException e) {
return false;
} catch (InterruptedException e) {
return false;
}
}
This is related to this question: Catch multiple exceptions at once?
The answer there is good. The key is that if you catch Exception then you should handle each of the cases that you are aware of and throw all the rest. That is, simply catching Exception in your example and returning false would not be a good idea. You may inadvertently catch some exception you didn't mean to.
Using your example, here is my suggested code:
public static boolean isNonsense2(String className) {
try {
Class.forName(className);
String.class.getConstructor(String.class);
className.getBytes("UTF-8");
MessageDigest.getInstance("SHA-1").wait();
return true;
} catch (Exception e) {
if (e instanceof ClassNotFoundException
|| e instanceof NoSuchMethodException
|| e instanceof SecurityException
|| e instanceof UnsupportedEncodingException
|| e instanceof NoSuchAlgorithmException
|| e instanceof InterruptedException) {
return false;
} else {
throw e;
}
}
}
I think there is no complete clear answer. In your case I would code it like this:
public static boolean isNonsense1(String className) {
if(slassname==null) throw new IllegalArgumentException("className must not be null");
try {
Class.forName(className);
String.class.getConstructor(String.class);
className.getBytes("UTF-8");
MessageDigest.getInstance("SHA-1").wait();
return true;
} catch (ClassNotFoundException e) {
throw new IllegalArgumentException("provided class " + className + " not found");
} catch (Exception e) {
return false;
}
}
For my flavor, throwing a NullPointerException is always bad, thats why I throw the IllegalArgumentException
If you are not interested in handling the exception (which you should as per best practices) don't bother with the explicit catches. The whole point of being able to handle specific exceptions is to enable you to handle them correctly.