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.");
}
Related
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
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)
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();
}
}
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);
}
}
}
}
I do not know how to successfully try and catch the exception. As you can see I already started the try-catch statement but do not know how to finish it. I get the error " tractorException.java:83: error: unreported exception tractorException; must be caught or declared to be thrown
setVehicleID(0); "
import java.io.*;
import java.util.*;
import javax.swing.*;
public class tractorException extends Exception {
protected int VehicleID;
public int setVehicleID(int VehicleID) throws tractorException {
if (VehicleID <= 0 || VehicleID > 100000) {
throw new tractorException();
} else {
this.VehicleID = VehicleID;
return this.VehicleID;
}
}
public int getVehicleID() {
return this.VehicleID;
}
tractorException() {
setVehicleID(0);
}
public static void main (String[] args) {
try {
throw new Exception("Something went wrong!!");
} catch (Exception e) {
}
Change your main method to:
public static void main (String[] args) {
try {
throw new tractorException(); // infinite loop ensues
} catch (Exception e) {
// this catch doesn't matter
}
}
The infinite loop occurs because tractorException's constructor calls setVehicleID(0), which in turn calls throw new tractorException(), which, as you guessed, calls setVehicleID(0) ... to infinity and beyond.
A function that throws exception must be caught or declared to be thrown. The issue you have with your code is in the line setVehicleID(0); as stated in the error log you posted.
Since setVehicleID() method throws exception, any time you call this function, it must be caught or re-throw. To fix your error, you need to surround this call with try catch:
tractorException()
{
try{
setVehicleID(0);
}
catch( tractorException e ) {
// Do something with error
}
}
try enter this
you cannot call Directly setVehicleID method because it is risky Method
tractorException() {
try{
setVehicleID(0);
}catch(Exception e){
}
}