Exception handling in Smart-Cloud framework is implemented based on my article Exception Handling in Real-Life Java Applications published on DZone.com.
Exception Handing Bullet Points:
-
Always have only one catch statement
-
Never catch Runtime exception
-
In the catch statement just call JK.handle(e); the framework will handle the rest.
-
If you are handling an exception inside method that should return value, it is safe to return null, check the following example.
Example 1:
package com.app;
import com.jk.util.JK;
public class ExceptionExample1 {
public static void main(String[] args) {
//Throw nullpointer exception and handle with default handler, which log the error then through runtime exception
try {
String name = null;
name.length();
} catch (Exception e) {
JK.handle(e);
}
}
}
Custom Exceptions Handling
-
Create Custom Handler
package com.app; import javax.swing.JOptionPane; import com.jk.util.exceptions.handler.ExceptionHandler; import com.jk.util.exceptions.handler.JKExceptionHandler; @ExceptionHandler public class ArrayIndexExceptionHandler implements JKExceptionHandler<ArrayIndexOutOfBoundsException> { @Override public void handle(ArrayIndexOutOfBoundsException throwable, boolean throwRuntimeException) { JOptionPane.showMessageDialog(null, "My ArrayIndexException Handler"); } }
-
Register Handler:
package com.app;
import com.jk.util.JK;
import com.jk.util.exceptions.handler.JKExceptionHandlerFactory;
public class ExceptionExample2 {
public static void main(String[] args) {
JKExceptionHandlerFactory.getInstance().registerHandlers("com.app");
//Throw nullpointer exception and handle with custom handler, which show the message in JOptionPane
try {
int arr[]=new int[0];
int x=arr[1];
} catch (Exception e) {
JK.handle(e);
}
}
}
For more details, check the DZone article at: https://dzone.com/articles/exception-handling-in-real-life-applications |