propagating error upwards in java - java

I have a main class where I have something like
void FooBar(String s){
try {
parseString(s);
} catch (Exception e) {
e.printStackTrace();
System.err.println("Error: " + e.getMessage());
context.getCounter(Counters.ERROR).increment(1); // this increment doesnt increases
}
}
parseString is
void ParseString(String s){
if (matcher.matches()) {
} else {
//throw exception
try {
throw new Exception("bad formatted N-triples");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
But for some reason, the error is not propagated upwards. In my FooBar method the error counters are not incremented even if the function gets bad formatted data.
How do I propagate this exception upwards?

But for some reason, the error is not propagated upwards...
The reason it is not propagated upwards is that you caught it. Exceptions stop propagating when they are caught.
Either don't catch it in parseString, or rethrow it in the handler; e.g. e.printStackTrace(); throw e;
However, this is likely to get you into more problems, specifically because of the exception you are catching / throwing here. The problem is that Exception is the root of all checked exceptions:
Since it is a checked exception, the method parseString must declare that it throws the Exception if you want to the exception to propagate.
But throws Exception is saying that this method could throw any possible checked exception ... which makes life difficult for the caller. (Not in this example ... but in general.)
My advice is as follows:
Avoid creating / throwing Exception. Pick a more specific (checked or unchecked) exception that reflects the meaning of the "exceptional event" you are trying to report ... or implement your own exception class. In this case throwing IllegalArgumentException would probably be better, though that is an unchecked exception.
Avoid situations where you need to propagate Exception.
Be careful when you catch Exception. It catches every (non-Error) exception, including all of the unchecked ones; i.e. RuntimeExecption and its subclasses.

You either don't catch it in ParseString, or you rethrow it with throw e;
Once an exception is caught, it doesn't get propagated unless you throw it again.

Examine what you're doing here:
try {
throw new Exception("bad formatted N-triples");//You throw an exception!
} catch (Exception e) {//And immediately catch it!
e.printStackTrace();
}
Because the exception is caught, it will not propagate. Instead, remove the try/catch block and simply throw the exception:
void ParseString(String s){
if (matcher.matches()) {
//code for reasons
} else {
//throw exception
throw new Exception("bad formatted N-triples");
}
}
Note that this is actually bad practice. You want to say something about your exception, and declare it:
void ParseString(String s) throws IllegalArgumentException {
if (matcher.matches()) {
//code for reasons
} else {
//throw exception
throw new IllegalArgumentException("bad formatted N-triples");
}
}
The surrounding function should know how to cope with that exception explicitly, rather than just throwing it's hands up because it's a general exception.

You shouldn't surround your error with try/catch:
void ParseString(String s){
if (matcher.matches()) {
}
else{
//throw exception
throw new Exception("bad formatted N-triples");}
}
}
When you throw the error, it's caught in the catch statement within parseString method, which is why isn't isn't propagated to the top.
Ideally, you'd do:
void ParseString(String s) throws Exception {
if (matcher.matches()) {
}
else{
//throw exception
throw new Exception("bad formatted N-triples");}
}
}

Related

How to call a method that throws an exception in catch block?

I am trying to have an HandleException method that can handles various exceptions.
The problem is, my function returns a value. But if I use HandleException in my catch block, Java complains that the function does not return a value even though my HandleException always throw an exception.
What is a good way to fix this? Thanks!
Here is a sample code.
public class MyException {
static int foo(int num) throws Exception {
try {
return bar(num);
} catch (Exception e) {
handleException();
// throw new Exception("Exception in foo", e);
}
}
static int bar(int num) throws IllegalArgumentException {
if (num < 0) {
throw new IllegalArgumentException("Num less than 0");
}
return num;
}
static void handleException(Exception e) throws Exception {
System.err.println("Handling Exception: " + e);
throw new Exception(e);
}
public static void main(String[] args) throws Exception {
int value = foo(-1);
}
}
In my original class, I have lot of methods that have this format.
try {
...
} catch (Exception1) {
Log exception
throw appropriate exception
} catch (Exception2) {
Log exception
throw appropriate exception
}
I am trying to comeup with a cleaner way to write the catch blocks.
This is because the exception that was thrown on handleException is already caught by the catch block of the foo method. Thus the foo method no longer throws an Exception making the catch block return nothing. So if the bar method throws an exception it will go to the catch block but since the catch block is not returning anyting, Java executes the lines after the catch block but when it reaches the end it throws an error that "the method must return a result of type int" since you do not have a return statement.
You should change this part.
public class MyException {
static int foo(int num) throws Exception {
try {
return bar(num);
} catch (Exception e) {
throw handleException(e); // this will throw the exception from the handleException
// throw new Exception("Exception in foo", e);
}
}
static int bar(int num) throws IllegalArgumentException {
if (num < 0) {
throw new IllegalArgumentException("Num less than 0");
}
return num;
}
// This method now returns an exception, instead of throwing an exception
static Exception handleException(Exception e) {
System.err.println("Handling Exception: " + e);
return new Exception(e);
}
public static void main(String[] args) throws Exception {
int value = foo(-1);
}
}
In my original class, I have lot of methods that have this format... I
am trying to come up with a cleaner way to write the catch blocks.
I think the issue is more to do with understanding how the exceptions are handled in applications; its a design issue, in general.
Consider the method: int foo(int num) throws Exception
The method foo returns a value, catches an exception/handles and also throws an exception. Consider these aspects.
If the method runs normally, without errors, it returns a value. Otherwise, if there is a problem with its logic, throws an exception within the method, catches it and handles it within the catch-block of the method. The method also throws an exception.
There are two options here to consider:
Re-throw an exception, like a custom business/application exception (just log it and re-throw the same or a custom exception), which needs to be handled elsewhere - that is in a calling method up the stack.
Handle the exception: This means that the method takes care of the exception. Some business/application logic happens within the exception handling. And, the method returns a value.
The purpose of a method throwing an exception is that it is handled elsewhere, like in a calling method. The handling can be like recovering from the exception problem or displaying a message or aborting a transaction or whatever the business logic defines.
Is the exception thrown because of a business logic issue? If so it is likely that you show a message to the user or do some other logic about it and/take further steps to recover from it - as the business rules permit it.
In case the exception is thrown as a result of a situation which is not recoverable by the application's logic, do appropriate actions.
Ultimately, you have to have a clear requirement about why an exception is thrown, what you do with the exceptions thrown and how you handle them in the application. The application/logic/rules requirement influences in designing the exception handling in the code.
Notes (edit-add):
There are quite a few articles which explain about exception handling
in business application out there on the net. One can try a search
string like "Java exceptions best practices". Here is one such
article which has some useful info: Effective Java
Exceptions.
There is also the try-catch-finally construct to consider (along with various new exception features introduced with Java 7).
foo method's return type is int and return type of handleException is void, that is why compiler gives error.
(1) Here you could solve this as follows:
Throw exception as is again.
try{
return bar(num);
}
catch(Exception e){
handleException(e);
throw e;
}
(2) Moreover if you want to throw new created exception then change return type of handleException to Exception. Use
throw handleException(e);

Throwing Exceptions from Exception class in java

Ok ... So I am learning about exceptions in java and i am currently at throw statements. I throw an exception of Exception class, and then re-throw it from the catch block again to handle it in the main function. But whenever i throw it as Exception class, i always get an Error in the catch block(where i re-throw it to be handled in main).But as soon as i change the thrown and caught Exceptions to some particular Exceptions like NullPointerException, it works!
Error Code:
class ThrowingExceptions {
static boolean enable3dRendering = false;
public static void main(String [] com) {
try {
renderWorld();
}
catch(Exception e) {
System.out.println("Rendering in 2d.");
}
}
static void renderWorld() {
try{
if(!enable3dRendering) {
System.out.println("3d rendering is disabled. Enable 3d mode to render.");
throw new Exception("3d mode Disabled.");
}
else {
System.out.println("The World is Empty!");
}
}
catch(Exception e) {
System.out.println("Please handle the error");
throw e; // It gives me an error here
}
}
}
Working Code:
class ThrowingExceptions {
static boolean enable3dRendering = false;
public static void main(String [] com) {
try {
renderWorld();
}
catch(NullPointerException e) {
System.out.println("Rendering in 2d.");
}
}
static void renderWorld() {
try{
if(!enable3dRendering) {
System.out.println("3d rendering is disabled. Enable 3d mode to render.");
throw new NullPointerException("3d mode Disabled.");
}
else {
System.out.println("The World is Empty!");
}
}
catch(NullPointerException e) {
System.out.println("Please handle the error");
throw e;
}
}
}
Why doesn't it work with Exception class and worked with its subclass??
Note :- The error i get in the error code is Unhandled exception type Exception
Runtime exceptions extend RuntimeException. They don’t have to be handled or declared.
They can be thrown by the programmer or by the JVM.
Checked exceptions have Exception in their hierarchy but not RuntimeException. They
must be handled or declared. They can be thrown by the programmer or by the JVM.
Errors extend the Error class. They are thrown by the JVM and should not be handled or
declared.
When method throws checked exception (1) you should handle or rethow it.
When method throws uncheked exception (2) you can handle or rethrow it, but it's not obligatory.
But whenever i throw it as Exception class, i always get an Error in
the catch block(where i re-throw it to be handled in main)
It means that your method is throwing checked exception which should be handled or rethrowed.
Handling:
public class Main {
public static void main(String[] args) {
try {
throw new Exception();
} catch (Exception e) {
try {
throw new Exception();
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
}
Rethrowing:
public class Main {
public static void main(String[] args) throws Exception {
try {
throw new Exception();
} catch (Exception e) {
throw new Exception();
}
}
}
In your case:
// You declaring that the caller should handle exception
static void renderWorld() throws Exception {
try {
if(!enable3dRendering) {
System.out.println("3d rendering is disabled. Enable 3d mode to render.");
throw new Exception("3d mode Disabled.");
} else {
System.out.println("The World is Empty!");
}
} catch(Exception e) {
System.out.println("Please handle the error");
// You cannot just throw uncheked exception here
// You should handle it yourself or a caller should do it
throw e;
}
}
Changing
static void renderWorld() { ... }
to
static void renderWorld() throws Exception { ... }
should fix this. This is for the reason that runtime exception are unchecked exceptions.
Would recommend you to read about the Checked and Unchecked exception in details here - Java: checked vs unchecked exception explanation.
It's because they are several Exception classes which are inherited from the class Exception. Each can be throwed, catched but they divide into two groups:
Checked and unchecked exceptions:
An unchecked exception doesn't need to be handled and the
NullPointerException which you tried is from that group, so you don't need to care about it technically.
A checked exception need to be handled every time or it won't
compile, these exceptions are like IOException.
Since the base Exception Object can be checked and unchecked as well the compiler cares about that it should be handled everytime.
If you give it a try and change the NullPointerException to IOException it won't compile either cause it is a Checked Exception. So it was just random, that you exactly find one type of Exception which your code can be work without compile error.
For more info visit my blog post about it:
http://www.zoltanraffai.com/blog/?p=93

Java: Issue with try-catch block with child class

I’m developing a web service code in Java (Eclipse Neon), I’ve two model classes for data assignment operations as shown here.
An editor is forcing me to remove try catch block from the constructor of class ‘ChatHistoryModel’ with the message: Unreachable catch block for JSONException. This exception is never thrown from the try statement
body.
If I remove the try-catch block, it will result in a code crash, when data assignment operation fails to assign data (a nil value). block if with variable is_group_chat throws null pointer exception.
How to handle this situation.
class TestHistoryModel extends TestModel {
private Boolean is_read, is_group_chat;
public TestHistoryModel(JSONObject jsonObject){
super(jsonObject);
try {
// value assignment operations
if (is_group_chat){ // Null pointer exception line
}
} catch (JSONException e) { // Error line
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class TestModel {
public TestModel(JSONObject jsonObject){
try {
// value assignment operations
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Here is a snapshot of error for catch block of class - TestHistoryModel
1 JSONException
JSONException is a checked-exception. That means that you can't catch it if it is never thrown in the try statement. You can remove it as it is not necessary. Read that JLS Chapiter to get more information.
2 NullPointerException
Accessing a Boolean instance like you do if(is_group_chat) is the equivalent to if(is_group_chat.booleanValue()), as it is null, you get that NullPointerException.
Check if the instance is null before checking it
Use a boolean insteand of the auto-boxed class
See OH GOD SPIDERS answer to see an alternative condition
You are getting the "Unreachable catch block" message because JSONException is a checked exception and nothing inside your try block is declared to be able to throw that JSONException. So this Exception will never be thrown inside your try block and the catch block never used.
Since the try catch block is unnecessary and won't fix your original problem you should simply remove it.
You are getting a NullPointerException because you are using a Boolean object that is null and Java will try to autounbox it into a small boolean.
To make it NullPointerException safe change
if (is_group_chat)
to
if (Boolean.TRUE.equals(is_group_chat))
If is_group_chat is still null the method Boolean.TRUE.equals will return false.
Your try catch blocks can be removed and really are the wrong way to solve this problem.
Another solution would bee to change is_group_chat to a small boolean. But keep in mind that those will be initialized with false as a default value.
In Java, there are two types of exceptions: checked and unchecked. Checked exceptions extends from Exception while unchecked from RuntimeException. If some method is throwing checked exception, that method must have in signature throws {SomeCheckedException} unless it handles this exception in method body. This way we are saying: take extra care, this method may fail.
Here is an example how to handle checked exceptions:
public List<String> getFileLines(Path filePath) throws IOException {
// this line is throwin checked exception "IOException" therefore,
// we need to rethrow this exception since it is not handled by try-catch
// from this moment, exception handling will be left on "getFileLines" caller
return readAllLines(filePath, StandardCharsets.UTF_8);
}
public List<String> getFileLinesOrNull(Path filePath) {
try {
// here IOException is caught, so we don't have to rethrow this exception
return readAllLines(filePath, StandardCharsets.UTF_8);
} catch (IOException e) {
return null; // return null if file reading failed...
}
}
Using methods:
public void getFileLinesTest() {
try {
// we are forced to write try-catch since method signature contains "throws IOException"
List<String> lines = getFileLines(somePath);
catch (IOException e) {
System.out.println("Some error occurred");
}
}
public void getFileLinesOrNullTest() {
List<String> lines = getFileLinesOrNull(somePath);
if (lines == null) {
System.out.println("Something went wrong...");
}
}
If we are handling checked exception, but there is no line which throws this exception, than code will not compile. Compiler knows if method has "throws ..." in signature, so compiler can easily identify such an error (therefore we are calling such an exceptions as compile-time exception):
public List<String> getFileLines() {
try {
return Collections.emptyList();
} catch (IOException e) { // COMPILATION ERROR!
// handling checked exception, but Collections.emptyList(); does not throw IOException
// method signature of the Collections.emptyList() is following:
// public static List<E> emptyList();
// as you can see there is no "throws IOException"
return null;
}
}
Example above is your case, since JSONException extends from Exception, so it is checked exception, while in your code, there is no line which throws such exception in try block.
However, TestHistoryModel constructor is throwing NullPointerException which is unchecked since it extends from RuntimeException. These exceptions have no "throws" in method signature so compiler will not force us to handle such an exceptions by try-catch block. Here is an example:
public int getLength(String s) {
if (s == null) {
// NullPointerException extends from RuntimeException = we are not forced to write
// add "throws NullPointerException " in getLength signature
throw new NullPointerException();
}
return s.length();
}
Handling of runtime-exceptions is optional:
public void getLengthTest() {
int length = getLength(null); // will throw NullPointerException
try {
length = getLength(null);
} catch(NullPointerException e) {
System.out.println("null argument");
}
}
Note, we do not have to write if (s == null) in getLength method, since s.length() will automatically throw NullPointerException if argument is null
and we are trying to call method on null. Exactly this happens in your constructor, because of this line if (is_group_chat). Field is_group_chat has Boolean type. Boolean is reference-type unlike boolean which is primitive-type. Not initialized "reference-type" variables are by default null. Therefore if (is_group_chat) is if (null) which is throwing NullPointerException.

Exception is never thrown in body of corresponding try statement

I have a problem with exception handling in Java, here's my code. I got compiler error when I try to run this line: throw new MojException("Bledne dane");. The error is:
exception MojException is never thrown in body of corresponding try statement
Here is the code:
public class Test {
public static void main(String[] args) throws MojException {
// TODO Auto-generated method stub
for(int i=1;i<args.length;i++){
try{
Integer.parseInt(args[i-1]);
}
catch(MojException e){
throw new MojException("Bledne dane");
}
try{
WierszTrojkataPascala a = new WierszTrojkataPascala(Integer.parseInt(args[0]));
System.out.println(args[i]+" : "+a.wspolczynnik(Integer.parseInt(args[i])));
}
catch(MojException e){
throw new MojException(args[i]+" "+e.getMessage());
}
}
}
}
And here is a code of MojException:
public class MojException extends Exception{
MojException(String s){
super(s);
}
}
Can anyone help me with this?
A catch-block in a try statement needs to catch exactly the exception that the code inside the try {}-block can throw (or a super class of that).
try {
//do something that throws ExceptionA, e.g.
throw new ExceptionA("I am Exception Alpha!");
}
catch(ExceptionA e) {
//do something to handle the exception, e.g.
System.out.println("Message: " + e.getMessage());
}
What you are trying to do is this:
try {
throw new ExceptionB("I am Exception Bravo!");
}
catch(ExceptionA e) {
System.out.println("Message: " + e.getMessage());
}
This will lead to an compiler error, because your java knows that you are trying to catch an exception that will NEVER EVER EVER occur. Thus you would get: exception ExceptionA is never thrown in body of corresponding try statement.
As pointed out in the comments, you cannot catch an exception that's not thrown by the code within your try block. Try changing your code to:
try{
Integer.parseInt(args[i-1]); // this only throws a NumberFormatException
}
catch(NumberFormatException e){
throw new MojException("Bledne dane");
}
Always check the documentation to see what exceptions are thrown by each method. You may also wish to read up on the subject of checked vs unchecked exceptions before that causes you any confusion in the future.
Any class which extends Exception class will be a user defined Checked exception class where as any class which extends RuntimeException will be Unchecked exception class.
as mentioned in User defined exception are checked or unchecked exceptions
So, not throwing the checked exception(be it user-defined or built-in exception) gives compile time error.
Checked exception are the exceptions that are checked at compile time.
Unchecked exception are the exceptions that are not checked at compiled time
Always remember that in case of checked exception you can catch only after throwing the exception(either you throw or any inbuilt method used in your code can throw) ,but in case of unchecked exception You an catch even when you have not thrown that exception.

Why try/catch around throwable?

In trying to refactor some I code I attempted to throw the exception in the catch clause like so -
try {
....
}
catch(Exception exception){
.....
throw exception
}
However when I attempted to throw the exception on line "throw exception" the compiler complained with a message that I needed to surround my throw clause in a new try/catch like so -
try
{
....
}
catch (Exception exception)
{
.....
try
{
throw exception
}
catch (Exception e2)
{
...
}
}
Why does the compiler require this and what use does it provide ?
Thanks
The exception java.lang.Exception is a checked exception. This means that it must either be declared in the throws clause of the enclosing method or caught and handled withing the method body.
However, what you are doing in your "fixed" version is to catch the exception, rethrow it and then immediately catch it again. That doesn't make much sense.
Without seeing the real code, it is not clear what the real solution should be, but I expect that the problem is in the original try { ... } catch handler:
If possible, you should catch a more specific exception at that point, so that when you rethrow it, it is covered by the method's existing throws list.
Alternatively, you could wrap the exception in an unchecked exception and throw that instead.
As a last resort, you could change the signature of the method to include Exception in the throws list. But that's a really bad idea, because it just pushes the problem off to the caller ... and leaves the developer / reader in the position of not knowing what exceptions to expect.
In Java, there is a distinction between checked and unchecked exceptions. An unchecked exception can essentially be thrown at any place in code and, if it's not caught somewhere, it will propagate up to the entry point of your application and then stop the process (usually with an error message and stack trace). A checked exception is different: The compiler won't let you just let it propagate, you need to either surround any code which might throw a checked exception with try-catch blocks (and "throw exception" is the simplest case if exception is an instance of a checked exception class) or you must mark the method which contains the call to code that might throw a checked exception with a "throws" declaration. If the desired behaviour is to throw an unchecked exception, then you'll need to wrap the exception in a RuntimeException. If the desired behaviour is to keep the exception checked, then you'll need to add a throws declaration to your current method.
In your original code, nothing catches the thrown exception. I would imagine you either have to specify that your function throws an exception or have another try/catch block as the compiler suggests to catch it.
Instead of
public void yourFunction(){
try {
....
}
catch(Exception exception){
.....
throw exception
}
}
try
public void yourFunction() throws Exception{
try {
....
}
catch(Exception exception){
.....
throw exception
}
}
My guess is that your trying to throw an exception sub class that isn't declared by the method as an exception type it can throw.
The following example works
package test.example;
public class ExceptionTest {
public static void main(String[] args) throws Exception{
try {
int value = 1/0;
} catch (Exception e) {
System.out.println("woops the world is going to end");
throw e;
}
}
}
However this example will give an error.
package test.example;
public class ExceptionTest {
public static void main(String[] args) throws RuntimeException{
try {
int value = 1/0;
} catch (Exception e) {
System.out.println("woops the world is going to end");
throw e;
}
}
}
Note in the second example I'm simply catching Exception not RuntimeException, it won't compile as I throw Exception which is an undeclared throws, even though I do declare RuntimeException.
Yes the exception is a RuntimeException but the compiler doesn't know that.
Just thought of a third working example to show you. This one also works because your throwing the same type as you declare. (note the only change is the catch block)
package test.example;
public class ExceptionTest {
public static void main(String[] args) throws RuntimeException{
try {
int value = 1/0;
} catch (RuntimeException e) {
System.out.println("woops the world is going to end");
throw e;
}
}
}
You need to understand the differences between all three of these answers

Categories

Resources