What is "chained exception facility" in java? [duplicate] - java

This question already has answers here:
What is the advantage of chained exceptions
(7 answers)
Closed 5 years ago.
i was reading about Throwable class from https://docs.oracle.com/javase/7/docs/api/java/lang/Throwable.html but i was not able to understand the chained exception facility. so somebody can please help me in this.

As Oracle doc says
Chained Exception Facility
It is common for Java code to catch one exception and throw another
And an example here from TutorialsPoint:
public class Main{
public static void main (String args[])throws Exception {
int n = 20, result = 0;
try {
result = n/0;
System.out.println("The result is"+result);
} catch(ArithmeticException ex) {
System.out.println ("Arithmetic exception occoured: "+ex);
try {
throw new NumberFormatException(ex);
} catch(NumberFormatException ex1) {
System.out.println ("Chained exception thrown manually : "+ex1);
}
}
}
}

Related

Custom exception not running , throwing other exception but not customly defined. What should I do for custom Exception? [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 1 year ago.
I was working on a program, a basic one that is based on command line input. I made a custom exception which should be triggered when users don't enter the second input, but whenever I do so, it throws array out of bound exception. What should I do in this situation?
package com.company;
public class Program2 {
public static void main(String[] args) throws MYex{
{
int a,b,c;
try
{
a=Integer.parseInt(args[0]); // getting data
b=Integer.parseInt(args[1]); // from command line
if( args[1]==null){
throw new MYex();
}
try
{
c=a/b;
System.out.println("Quotient is "+c);
}
catch(ArithmeticException ex)
{
System.out.println("Error in division !");
}
}
catch (MYex e){
System.out.println(e.toString());
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array out of bound!");
}
finally
{
System.out.println("End of the progarm!!!");
}
}
}}
class MYex extends Exception{
#Override
public String toString() {
return " oops a Exception occured";
}
}
If the user passes only one argument the args array has only one element. Therefore the exception already occurs when you try to access args[1].
To prevent this check args.length before accessing args[1]:
a=Integer.parseInt(args[0]); // getting data
if (args.length == 1) {
throw new MYex();
}
b=Integer.parseInt(args[1]); // from command line

How to catch a null pointer exception [duplicate]

This question already has answers here:
Catching nullpointerexception in Java [closed]
(5 answers)
Closed 2 years ago.
I have the code below and I am trying to catch an exception and print out something if the file == null so it doesn't throw an exception but I am having problems solving this.
public class Controller {
private ImageWindow IW = new ImageWindow(this);
private Model M = new Model(this.IW);
private File file = null;
public void openImage() {
File file = IW.ChooseImageFile();
if (file != null) {
M.loadImage(file);
}
this.IW.setVisible(true);
}
public static void main(String[] args) throws IOException {
SwingUtilities.invokeLater(() -> new Controller());
}
}
Usually I would use a try/catch statement for exception management in Java. Reference
try {
Enter code here
} catch (NullPointerException npe) {
System.out.println(“Error Message”);
}

finally block does not execute if exception is thrown [duplicate]

This question already has answers here:
Understanding checked vs unchecked exceptions in Java
(21 answers)
Closed 2 years ago.
finally block would execute if an exception is thrown in try block here:
public class ExceptionTest{
public static void main(String args[])
{
System.out.println(print());
}
public static int print()
{
try
{
throw new NullPointerException();
}
finally
{
System.out.println("Executing finally block");
}
}
}
output:
Executing finally block
Exception in thread "main" java.lang.NullPointerException
at ExceptionTest.print(ExceptionTest.java:11)
at ExceptionTest.main(ExceptionTest.java:4)
In the other hand finally won't be called in this code right here:
public class ExceptionTest{
public static void main(String args[])
{
System.out.println(print());
}
public static int print()
{
try
{
throw new Exception();
}
finally
{
System.out.println("Executing finally block");
}
}
}
output:
ExceptionTest.java:11: error: unreported exception Exception; must be caught or declared to be thrown
throw new Exception();
^
1 error
why it is cool with NullPointerException class but it complains when it comes to Exception class?
NullPointerException is an unchecked exception. Check this guide.
Here is an example of a try and catch block which catches everything:
try {
//Do Something
}
catch (Exception e) {
System.out.println("Something went wrong.");
}
finally {
System.out.println("The 'try catch' is finished.");
}

chain exception in catch block

I have the following java code :
public void someMethod(){
try{
// some code which generates Exception
}catch(Exception ex1) {
try{
// The code inside this method can also throw some Exception
myRollBackMethodForUndoingSomeChanges();
}catch(Exception ex2){
// I want to add inside `ex2` the history of `ex1` too
// Surely , I cannot set cause of `ex2` as `ex1` as `ex2`
// can be caused by it's own reasons.
// I dont want `ex1` details to be lost if I just throw `ex2` from my method
}
}
}
How to do it ?
EDIT : Actually this happens in my service layer and I have controller advice for logging. Hence I don't want to add 2 loggers here.
You can add ex1 to the supressed exceptions in ex2 via the method addSuppressed before rethrowing it.
Quick code example:
public static void main(final String[] args) {
try {
throw new IllegalArgumentException("Illegal Argument 1!");
} catch (final RuntimeException ex1) {
try {
throw new IllegalStateException("Illegal State 2!");
} catch (final RuntimeException ex2) {
ex2.addSuppressed(ex1);
throw ex2;
}
}
}
will produce the exception output:
Exception in thread "main" java.lang.IllegalStateException: Illegal State 2!
at package.main(Main.java:26)
Suppressed: java.lang.IllegalArgumentException: Illegal Argument 1!
at package.main(Main.java:20)

How to test exception is thrown with Junit [duplicate]

This question already has answers here:
JUnit right way of test expected exceptions
(4 answers)
Closed 5 years ago.
I would like to know how I can write a unit test to get the catch block covered for the following method. The FOM.create(data) is a static method.
public String getValue(Data data) {
try {
return FOM.create(data);
} catch (UnsupportedEncodingException e) {
log.error("An error occured while creating data", e);
throw new IllegalStateException(e);
}
}
Currently this is my unit test but it doesn't hit the catch block:
#Test (expected = UnsupportedEncodingException.class)
public void shouldThrowUnsupportedEncodingException() {
doThrow(UnsupportedEncodingException.class).when(dataService).getUpdatedJWTToken(any(Data.class));
try {
dataService.getValue(data);
}catch (IllegalStateException e) {
verify(log).error(eq("An error occured while creating data"), any(UnsupportedEncodingException.class));
throw e;
}
}
You can check throwable exception if exception does not caught before unit test. In your case you cant check UnsupportedEncodingException but can check IllegalStateException.
Unit test must looks like:
#Test (expected = IllegalStateException.class)
public void shouldThrowIllegalStateException() {
dataService.getValue(data);
}
if you wanna to check UnsupportedEncodingException you must testing FOM.create(data) method
You can use JUnits exception rule like this:
public class SimpleExpectedExceptionTest {
#Rule
public ExpectedException thrown= ExpectedException.none();
#Test
public void throwsExceptionWithSpecificType() {
thrown.expect(NullPointerException.class);
thrown.expectMessage("Substring in Exception message");
throw new NullPointerException();
}
}

Categories