run some logic after exception happen dynamically - java

I think that all Error and Exception type extend from Exception class so how could i watch exception when the application stopped working because i want to run some logic when the exception thrown
i am not just asking about try{} catch {} finally {}
if i want to make plugin to watch on any exception happen on application to run my logic
example
if you have application named X and you have library named Y how could library Y watch and run logic when X throw Exception without edit on logic of X code

Error and Exception classes are extended from Throwable class. Now If you want to catch exception, you can simply go with try-catch-(finally , If required) block. You must not catch Error, because error is something which you cannot recover, Below is the hierarchy, the Error and Exception are two different hierarchy except one thing that both are Throwable.

You can catch exception if you know the exception and execute your logic there. Or, you can write your logic in finally block after exception block. Eg:
try {
....
} catch (YourException e) {
....
} finally {
// your logic
}

Related

What does "error: unreported exception <XXX>; must be caught or declared to be thrown" mean and how do I fix it?

New Java programmers frequently encounter errors phrased like this:
"error: unreported exception <XXX>; must be caught or declared to be thrown"
where XXX is the name of some exception class.
Please explain:
What the compilation error message is saying,
the Java concepts behind this error, and
how to fix it.
First things first. This a compilation error not a exception. You should see it at compile time.
If you see it in a runtime exception message, that's probably because you are running some code with compilation errors in it. Go back and fix the compilation errors. Then find and set the setting in your IDE that prevents it generating ".class" files for source code with compilation errors. (Save yourself future pain.)
The short answer to the question is:
The error message is saying that the statement with this error is throwing (or propagating) a checked exception, and the exception (the XXX) is not being dealt with properly.
The solution is to deal with the exception by either:
catching and handling it with a try ... catch statement, or
declaring that the enclosing method or constructor throws it1.
1 - There are some edge-cases where you can't do that. Read the rest of the answer!
Checked versus unchecked exceptions
In Java, exceptions are represented by classes that descend from the java.lang.Throwable class. Exceptions are divided into two categories:
Checked exceptions are Throwable, and Exception and its subclasses, apart from RuntimeException and its subclasses.
Unchecked exceptions are all other exceptions; i.e. Error and its subclasses, and RuntimeException and its subclasses.
(In the above, "subclasses" includes by direct and indirect subclasses.)
The distinction between checked and unchecked exceptions is that checked exceptions must be "dealt with" within the enclosing method or constructor that they occur, but unchecked exceptions need not be dealt with.
(Q: How do you know if an exception is checked or not? A: Find the javadoc for the exception's class, and look at its parent classes.)
How do you deal with a (checked) exception
From the Java language perspective, there are two ways to deal with an exception that will "satisfy" the compiler:
You can catch the exception in a try ... catch statement. For example:
public void doThings() {
try {
// do some things
if (someFlag) {
throw new IOException("cannot read something");
}
// do more things
} catch (IOException ex) {
// deal with it <<<=== HERE
}
}
In the above, we put the statement that throws the (checked) IOException in the body of the try. Then we wrote a catch clause to catch the exception. (We could catch a superclass of IOException ... but in this case that would be Exception and catching Exception is a bad idea.)
You can declare that the enclosing method or constructor throws the exception
public void doThings() throws IOException {
// do some things
if (someFlag) {
throw new IOException("cannot read something");
}
// do more things
}
In the above we have declared that doThings() throws IOException. That means that any code that calls the doThings() method has to deal with the exception. In short, we are passing the problem of dealing with the exception to the caller.
Which of these things is the correct thing to do?
It depends on the context. However, a general principle is that you should deal with exceptions at a level in the code where you are able to deal with them appropriately. And that in turn depends on what the exception handling code is going to do (at HERE). Can it recover? Can it abandon the current request? Should it halt the application?
Solving the problem
To recap. The compilation error means that:
your code has thrown a checked exception, or called some method or constructor that throws the checked exception, and
it has not dealt with the exception by catching it or by declaring it as required by the Java language.
Your solution process should be:
Understand what the exception means, and why it could be thrown.
Based on 1, decide on the correct way to deal with it.
Based on 2, make the relevant changes to your code.
Example: throwing and catching in the same method
Consider the following example from this Q&A
public class Main {
static void t() throws IllegalAccessException {
try {
throw new IllegalAccessException("demo");
} catch (IllegalAccessException e){
System.out.println(e);
}
}
public static void main(String[] args){
t();
System.out.println("hello");
}
}
If you have been following what we have said so far, you will realise that the t() will give the "unreported exception" compilation error. In this case, the mistake is that t has been declared as throws IllegalAccessException. In fact the exception does not propagate, because it has been caught within the method that threw it.
The fix in this example will be to remove the throws IllegalAccessException.
The mini-lesson here is that throws IllegalAccessException is the method saying that the caller should expect the exception to propagate. It doesn't actually mean that it will propagate. And the flip-side is that if you don't expect the exception to propagate (e.g. because it wasn't thrown, or because it was caught and not rethrown) then the method's signature shouldn't say it is thrown!
Bad practice with exceptions
There are a couple of things that you should avoid doing:
Don't catch Exception (or Throwable) as a short cut for catching a list of exceptions. If you do that, you are liable catch things that you don't expect (like an unchecked NullPointerException) and then attempt to recover when you shouldn't.
Don't declare a method as throws Exception. That forces the called to deal with (potentially) any checked exception ... which is a nightmare.
Don't squash exceptions. For example
try {
...
} catch (NullPointerException ex) {
// It never happens ... ignoring this
}
If you squash exceptions, you are liable to make the runtime errors that triggered them much harder to diagnose. You are destroying the evidence.
Note: just believing that the exception never happens (per the comment) doesn't necessarily make it a fact.
Edge case: static initializers
There some situations where dealing with checked exceptions is a problem. One particular case is checked exceptions in static initializers. For example:
private static final FileInputStream input = new FileInputStream("foo.txt");
The FileInputStream is declared as throws FileNotFoundException ... which is a checked exception. But since the above is a field declaration, the syntax of the Java language, won't let us put the declaration inside a try ... catch. And there is no appropriate (enclosing) method or constructor ... because this code is run when the class is initialized.
One solution is to use a static block; for example:
private static final FileInputStream input;
static {
FileInputStream temp = null;
try {
temp = new FileInputStream("foo.txt");
} catch (FileNotFoundException ex) {
// log the error rather than squashing it
}
input = temp; // Note that we need a single point of assignment to 'input'
}
(There are better ways to handle the above scenario in practical code, but that's not the point of this example.)
Edge case: static blocks
As noted above, you can catch exceptions in static blocks. But what we didn't mention is that you must catch checked exceptions within the block. There is no enclosing context for a static block where checked exceptions could be caught.
Edge case: lambdas
A lambda expression (typically) should not throw an unchecked exception. This is not a restriction on lambdas per se. Rather it is a consequence of the function interface that is used for the argument where you are supplying the argument. Unless the function declares a checked exception, the lambda cannot throw one. For example:
List<Path> paths = ...
try {
paths.forEach(p -> Files.delete(p));
} catch (IOException ex) {
// log it ...
}
Even though we appear to have caught IOException, the compiler will complain that:
there is an uncaught exception in the lambda, AND
the catch is catching an exception that is never thrown!
In fact, the exception needs to be caught in the lambda itself:
List<Path> paths = ...
paths.forEach(p -> {
try {
Files.delete(p);
} catch (IOException ex) {
// log it ...
}
}
);
(The astute reader will notice that the two versions behave differently in the case that a delete throws an exception ...)
More Information
The Oracle Java Tutorial:
The catch or specify requirement
... also covers checked vs unchecked exceptions.
Catching and handling exceptions
Specifying the exceptions thrown by a method

Java Catch Block Without Try block is possible as I am throwing the Exception From a different class

Java Catch Block Without Try block is possible as I am throwing the Exception From a different class. If it is not possible then how I can determine which type of exception is it as from the previous class I am Just throwing the Exception e
To determine whitch exception it is, you can check it like
if(e instanceof IOException)
{
}
But why you dont use try-catch block?

Android - general exception catcher

I'm trying to integrate Facebook into my app so I followed all the instructions. When running it, after onResume event finishes, I get an exception that I can't catch from my code.
Is there a way to set a general exception catcher so no matter what, it will catch it?
The emulator does not throw any exception at all so I can't use it for this
Update: I found it here: Using Global Exception Handling on android
The error came from Facebook itself and it is related to working with proguard
try this solution:
create a class that implement Thread.UncaughtExceptionHandler (this
class going to handle with the uncaughtExceptions), lets call this
class ExceptionHandler.
create a class that extends Application,
lets call this class App, and don't forget to declare this in the
manifest file under application tag: android:name="your_package_path.App"
in your App class override the method onCreate(), and add this line: Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(this));
The Throwable class is the superclass of all errors and exceptions in the Java language.
If you catch a throwable you can catch all kind of errors and exceptions.
try {
// code
} catch(Throwable e) {
// handle throwable
}
However this is strongly not recommended and bad practise/design. You should never catch generic errors and exceptions. You should analyse your specific exception and solve the problem instead of simply ignoring it with try/catch!
There is a base Exception class. So if you do like this:
try {
...anything...
}catch(Exception e) {
e.printStackTrace();
}
you'll catch any exception that is thrown by any method called from within the try block.
But remember that exceptions aren't always thrown. Sometimes there's just no result to return, or something.

java throwing checked exceptions?

I am pretty sure that this worked before, but eclipse says there is error with it in throw line.
try{}
}catch(Exception e){
throw e; }
In my old student project I wrote :
try {
Class.forName("org.postgresql.Driver");
this.connection = DriverManager.getConnection(
DataSource.getURL(), DataSource.getUserName(), DataSource.getPassword());
} catch (ClassNotFoundException e) {
System.out.println("Could not find driver to connect to database. Please make"
+ "sure the correseponding postgreSQLjdbc library is added.");
throw e;
} catch (SQLException e) {
System.out.println("Username or password is not correct");
throw e;
}
and it was perfect.
Only this type works, but it is not what I want
throw new UnsupportedAddressTypeException();
Presumably your method is declared to throw UnsupportedAddressTypeException but not SQLException and ClassNotFoundException. Checked exceptions can only be thrown (including rethrowing an existing one) from methods which declare that they throw those exceptions or a superclass.
eclipse says its an error because:
The method which contains this block of code needs to have a declaration of "throws Exception"
The method either needs to handle the exception itself OR signal to other calling methods that it can throw an exception and they should handle it.
An alternate way of handling it would be to enclose the "throw e" in another try/catch block(method handling the exception itself).
Your uni code worked because the method which had these statements must have been declared like:
method x() throws ClassNotFoundException, SQLException
Without additional information with specifics on what exactly you are doing, the only generic solution I can give you is to rethrow your exception wrapped in an unchecked RuntimeException.
The code you included rethrows Exception, which is a checked exception. Unless the method this was incide was declared with "throws Exception" this could couldn't have worked in any Java version.
On another note, never log and rethrow. Do either one or the other. So your project code should've looked like:
....
} catch (SQLException e) {
throw RuntimeException("Username or password is not correct", e);
}
ClassNotFoundException or SQLException are checked exceptions. So are supposed to be handled somehow whenever they are thrown (even if manually using 'throw' keyword).
There are two ways to handle a checked exception :
1. Surround the code that could throw a checked exception within try-catch block.
2. Add throws clause after the method definition in which that particular code is written.
Now, here when you 'throw e' where e is either an instance of ClassNotFoundException or SQLException, it has to be handled in either of the above two ways.
However, UnsupportedAddressTypeException is an unchecked exception. So you need not handle it explicitly. You can just throw it anywhere and Java will take care of it.

How can we make our Userdefined Exception part of Compile Time

public class NoSufficientFundException extends Exception
{
String strValue;
public PositionException(String value) {
this.strValue = value;
}
}
For example if i do the above way, the exception NoSufficientFundException also includes RuntimeException.
Basically how to make Userdefined Exception as part of Compile Time.
You need to understand the difference between checked and unchecked exceptions. When an exception is checked then you need to wrap it around try-catch.
try{
// open File
new FileReader(...)
}catch(IOException e){
// handle a CHECKED exception
}
I think what you are asking is how to not have to check for this catch. These are called uncheced exceptions. You can do this by extending RuntimeException. You no longer to catch these exceptions, and instead the JVM will catch them and print the log.
It is "a part of compile time" now. You have to extend RuntimeException to get unckeched exceptions - not checked at compile time.

Categories