I am a C programmer and just learning some java recently because I am developing one android application. Currently I am in a situation. Following is the one.
public Class ClassA{
public ClassA();
public void MyMethod(){
try{
//Some code here which can throw exceptions
}
catch(ExceptionType1 Excp1){
//Here I want to show one alert Dialog box for the exception occured for the user.
//but I am not able to show dialog in this context. So I want to propagate it
//to the caller of this method.
}
catch(ExceptionType2 Excp2){
//Here I want to show one alert Dialog box for the exception occured for the user.
//but I am not able to show dialog in this context. So I want to propagate it
//to the caller of this method.
}
}
}
Now I wan to use call the method MyMethod() somewhere else in another class. If some one can provide me some code snippet how to propagate the exceptions to the caller of MyMethod() so that I can display them in a dialog box in the caller method.
Sorry If I am not so much clear and weird in the way of asking this question.
Just don't catch the exception in the first place, and change your method declaration so that it can propagate them:
public void myMethod() throws ExceptionType1, ExceptionType2 {
// Some code here which can throw exceptions
}
If you need to take some action and then propagate, you can rethrow it:
public void myMethod() throws ExceptionType1, ExceptionType2 {
try {
// Some code here which can throw exceptions
} catch (ExceptionType1 e) {
log(e);
throw e;
}
}
Here ExceptionType2 isn't caught at all - it'll just propagate up automatically. ExceptionType1 is caught, logged, and then rethrown.
It's not a good idea to have catch blocks which just rethrow an exception - unless there's some subtle reason (e.g. to prevent a more general catch block from handling it) you should normally just remove the catch block instead.
Don't catch it and rethrow again. Just do this and catch it in the place you want
public void myMethod() throws ExceptionType1, ExceptionType2 {
// other code
}
Example
public void someMethod() {
try {
myMethod();
} catch (ExceptionType1 ex) {
// show your dialog
} catch (ExceptionType2 ex) {
// show your dialog
}
}
Just rethrow the exception
throw Excp1;
You will need to add the exception type to the MyMthod() declaration like this
public void MyMethod() throws ExceptionType1, ExceptionType2 {
try{
//Some code here which can throw exceptions
}
catch(ExceptionType1 Excp1){
throw Excp1;
}
catch(ExceptionType2 Excp2){
throw Excp2;
}
}
Or just omit the try at all since you are no longer handling the exceptions, unless you put some extra code in the catch statements doing things with the exception before rethrowing it.
I always do it like this :
public void MyMethod() throws Exception
{
//code here
if(something is wrong)
throw new Exception("Something wrong");
}
then when you call the function
try{
MyMethod();
}catch(Exception e){
System.out.println(e.getMessage());
}
Related
Let's suppose I have this class:
public class Obj1{
...
public void do_Something(int someParameter) throws SomeException {
if(...) throw new SomeException();
...
}
...
}
then, somewhere
public class Obj2{
...
public void do_SomeOtherThing(Obj1 obj1){
obj1.do_Something();
//apparently the only solution is try-catching it directly, even if I'm not in the main...
...
}
I've learned that exceptions should only be thrown by METHOD, and catched by MAIN, so, my question is: is try-catch the unique way to handle sub-method exceptions, or the most external method (do_SomeOtherThing) will throw it, so that I can try-catch it directly in main, deleting the try-catch in Object2 class?
Basically, can I do as follows?
public static void main(String[] args){
Object1 obj1 = new Object1();
Object2 obj2 = new Object2();
try{
obj2.do_SomeOtherThing(obj1);
}
catch(SomeException e){
...
}
}
or not?
A checked exception is part of the contract that a method has with its caller, and a thrown exception will always need to be handled one way or another.
The correct answer depends on the exact situation:
The caller can handle the exception:
String getStringFromRemoteServer() throws IOException { ... }
String getConfigString() {
try {
return getStringFromRemoteServer();
} catch (IOException e) {
LOG.warn("Failed to contact server, using local version.", e);
return getLocalString();
}
}
In this case we have an alternative source of the data we need, so if the preferred method fails we catch the exception, log it (so that we know a problem exists with our network) and call the alternative.
The exception is fatal, and we don't want any function higher in the call tree to try to handle it.
Configuration parseConfiguration(String configString) throws ParseException { ... }
void loadConfiguration() {
try {
this.globalConfig = parseConfiguration(getConfigString());
} catch (ParseException e) {
throw new RuntimeException("Corrupted config", e);
}
}
In this case an exception means that the configuration of our application is fatally broken. There is no point in trying to handle this error, and no point in any of our callers trying to handle it, so declaring throws on loadConfiguration() would just be confusing clutter. We wrap the exception in a RuntimeException and rethrow it. Note that we don't log it -- there will be some top level reporting of uncaught exceptions, so logging it here would be repetition.
It is still valuable to have parseConfiguration() throw a checked exception, because when we are calling it from the interactive configuration editor we catch the exception and display an error message to the user.
Maybe our caller can handle the exception.
int stringToInteger(String s) throws BadNumberException { ... }
String decimalStringToHexString(String s) throws BadNumberException {
return intToHex(stringToInteger(s));
}
In this case we are not changing the meaning of the exception -- decimalStringToHexString is converting a number from a string, and one possible outcome is that the string is illegal. Our caller needs to be aware of that as a possible outcome, just as callers of stringToInteger() are, so we simply declare the exception and let our caller handle it. Our caller knows the context they are using the number in, so they can decide how to handle the exception.
A couple of rules:
Never completely ignore an exception (OK, maybe InterruptedException). If you write try { ... } catch (Exception e) {} the empty catch clause will make it hard to spot why your code doesn't work.
When you wrap an exception, always include the original exception as the cause.
For debugging purposes i want my Java application to upload a log file on my MySql database whenever a catch clause is executed, regardless of which exception is thrown.
The worst solution i thought to was to add my uploader method into each catch in my code (as I already did for the creation of my log file) . This is obviously not elegant method, as long it's repeated code. So my question is: it exist someway (maybe in project proprieties) to set a default operation to be executed whenever a catch clause is met?
There's no way to create a default behavior without typing it into it... Create a global method so you can call it with one line.
One option would be to use a logging framework (no matter if you write this your self or use an existing solution), so you can do:
try{}
catch(Exception e) {Logger.logExceptionToDatabase(e); }
In this you could handle the upload into your database. However I do not thinkt that it is very useful to upload error logs into your database each time a catch block gets executed. I would write them to seperate text logs and collect them and only persist them to a database from time to time or by user request.
To the question itself: This is not possible, however there is a finally block which gets executed after the according try block (as long as the JVM is not terminated within the try block). Maybe you could introduce some TransactionResult and do a logging for each success and failure and than do:
TransactionResult transactionResult;
try{
//do work and at the last line in the try after each operation that could
have failed has been executed set your transactionResult variable
transactionResult = new SuccessTransaction();
}
catch(Excpetion e) { transactionResult= new FailureTransaction();}
finally {Logger.logTransaction(transactionResult); }
and the according classes:
public interface TransactionResult{
public void writeLog();
}
and an example of an transaction result:
public class SuccessTransaction implements TransactionResult{
private String resultStatus;
public SuccessTransaction() { this.resultStatus = "success"; }
public void writeLog() { System.out.println(this.resultStatus); } //or whatever you want to do with your result
}
same goes for your failure instance.
Update
As you stated that there are many Exceptions, you could also pass your Exception to your concrete FailureTransaction and than simply write that message out or collect all the failures in a list and then you can trace which exceptions have been triggered.
You could do something like the following:
public static void myMethod() throws FooException, BarException {
throw new FooException();
}
// if you don't care about specific catch cases:
public static void main(String[] args) throws FooException, BarException {
try {
myMethod();
} catch (Exception x) {
x.printStackTrace(); // default behavior on exception
throw x; // let the specific exception bubble up the call stack
// The compiler knows that this will be either FooException or BarException
}
}
// if you need to also handle specific catch cases:
public static void main(String[] args) throws BarException {
try { // outer try-catch, to handle specific exceptions
try { // inner try-catch to handle default catch behavior
myMethod();
} catch (Exception x) { // Or } catch (FooException | BarException x) {
x.printStackTrace(); // default behavior on exception
throw x; // let the exception bubble up to the specific catch clauses.
// The compiler knows that this will be either FooException or BarException
}
} catch (FooException e) {
System.err.println("Doing something specific to 'FooException'");
// could re-throw if you want to
} catch (BarException e) {
System.err.println("Doing something specific to 'BarException'");
throw e; // only re-throw if you want to
}
}
If you don't need to do anything for specific exceptions then the first main should work just fine.
If you do want to handle specific exceptions on top of your default catch behavior, then just re-throw the exception, catch what it is specifically, and handle that specific case.
You can always re-throw the exception when you want it to bubble further up the call stack.
Suppose, I have a method:
private void someMethod() {
try {
//Do something here
}
catch (NullPointerException ex) {
System.out.println("error");
}
}
Now, I want to use this method somewhere else:
private void newMethod() {
someMethod();
JOptionPane.showMessageDialog(null, "Exception didn't occur");
}
Now, I want that if exception occurs in someMethod(), then newMethod() will not advance further, I mean, the JOptionPane message will not be shown in this case.
What will be the best way to do that? I have found a way by throwing another NullPointerException in catch block of someMethod() and then handling that from newMethod(). The code below demonstrates that:
private void someMethod() {
try {
//Do something here
}
catch (NullPointerException ex) {
System.out.println("error");
throw new NullPointerException("error");
}
}
private void newMethod() {
try {
someMethod();
JOptionPane.showMessageDialog(null, "Exception didn't occur");
}
catch (NullPointerException ex) {
System.out.println("error");
}
}
But, by this method, I am facing some difficulties for other cases. I guess there are better ways to achieve that. Thanks anyway.
You don't need to handle the exception inside someMethod. Instead you can declare the exception in this method's throws clause (if it is a checked exception) and let newMethod handle it.
private void someMethod() throws SomeCheckedException {
//Do something here
}
In case of NullPointerException, you don't need to do above, as it is an unchecked exception. Don't catch it inside someMethod, instead have try-catch inside newMethod.
It is good practice if your function intend to throw exception make it part of function declaration. So recommendation is to change someMethod() to private void someMethod() throws <exception Name>.
Depends on your requirement you can handle the exception in same method and throw another exception, or re throw same exception and handle it in another function.
In case you are re-throwing the same exception syntax is as follows:
private void someMethod() throws WhateverException {
try {
//Do something here
}
catch (WhateverException e) {
throw e;
}
}
I'm studying for a CS exam this Friday and have hit a bump in the road here. The question asks me to handle the exception and then propagate the exception using two different methods, but I was under the impression they were the same thing. Can anyone help? The practice question is listed below.
You are given the following class:
public class ReadData {
public void getInput() {
getString();
getInt();
}
public void getString() throws StringInputException {
throw new StringInputException();
}
public void getInt() throws IntInputException {
throw new IntInputException();
}
}
class StringInputException extends Exception {}
class IntInputException extends Exception {}
The code above will result in compilation errors in getInput() method.
Rewrite getInput() method using two different techniques:
Method 1 - Handle the exception
Method 2 - Propagate the exception
so that the code compiles.
They are not the same thing. Propagation basically means re-throwing the exception, that is, allowing somewhere further up in the code to handle it; generally this is done if nothing can be done about the exception at the current level. Handling the exception means catching it and actually doing something about it - informing the user, retrying, logging - but not allowing the exception to go any further.
class Example {
// a method that throws an exception
private void doSomething() throws Exception {
throw new Exception();
}
public void testHandling() {
try {
doSomething();
} catch (Exception e) {
// you caught the exception and you're handling it:
System.out.println("A problem occurred."); // <- handling
// if you wouldn't want to handle it, you would throw it again
}
}
public void testPropagation1() throws Exception /* <- propagation */ {
doSomething();
// you're not catching the exception, you're ignoring it and giving it
// further down the chain to someone else who can handle it
}
public void testPropagation2() throws Exception /* <- propagation */ {
try {
doSomething();
} catch (Exception e) {
throw e; // <- propagation
// you are catching the exception, but you're not handling it,
// you're giving it further down the chain to someone else who can
// handle it
}
}
}
"Handle the exception" means to catch it and do whatever is necessary to continue normally.
"Propagate the exception" means to not catch it and let your caller deal with it.
dictionary.com is your friend in this one.
Sometimes we have to deal with that pesky english language.
Handle means do something with the exception,
abort program ,
print error,
mess around with data ...
propagate it means forward it onto someplace else i.e. re throw it.
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