I am just wondering what the Java VM does with a Try-Catch. How does it execute it?
My best guess is that it is like a Linux system which when installing something does a test run and if no errors are found asks the user if he/she wants to proceed. In the case of a Try-Catch does it do a test run and if all is OK implement it?
It is much simpler than that - if any clause included in the try clause generates an error, the code in the catch clause (corresponding to that error - you can have multiple catch for a single try) will be executed. There is no way to know in advance if a particular clause will fail or not, only to try to recover after the error happens.
If you have ten clauses and the last one throws an error, the modifications performed by the first 9 will not be "reverted"!
try
{
//execute your code
}catch(Exception e)
{
//Log message
//IF you don't want to continue with the logic inside method, rethrow here.
}finally{
//Ir-respective of what the status is in above cases, execute this code.
}
//Continue with other logic in the method
.This is useful in cases where you want to determine part of your code need to be executed (or) not in exception case.
To understand more about how try-catch works in java read this tutorial.
The code which can give some unexpected result which the program can't handle is kept inside the try block,and to handle/catch the unexpected crashing of the program we use catch block.Where we declare type of Exception the code can throw
Eg:
int a;
try {
a=1/0;//program wil crash here
}catch(Exception e){
System.out.println("Division by zero ");//handling the crash here
}
It starts executing normally, w/o any checking. If any exception occurs, it will break out of the clause (like break in a loop), and immediately execute the catch, if no exception was found, it will skip the catch clause.
The finally clause, insures that it will be called no matter if an exception was thrown, or not. A practical example would be reading from a file or network, and close the streams, no matter if an exception was thrown or not.
Related
I am confused. Does it depend on the concrete situation? Or it has a universal standard? Could anyone give a summary to tell me when to use if-else, and when to use try...catch?
if else statements are for evaluating boolean expressions, for instance,
if(isWeekday){
return "wakeup#6:00AM";
}
else{
return "wakeup#10:00AM";
you would use an if else statement for data you know you have, and when you can easily compute a boolean expression. Some times, you aren't really sure what you're dealing with and could get errors trying to deal with it. In a case like this, you would use a try catch.
try{
Scanner data = new Scanner(new File("data.dat"));
} catch (IOException e){
e.printStackTrace();
}
In this scenario you can't really be sure that the file you want to get data from even exists, so therefore you can't perform any reasonable computation on it.
I guess this is too wide question, but from my point of view try...catch block must be used only in exceptional cases, the ones that you are not really expecting to happen, however, the application could recover from these situations. If-else is a completely normal block to allow your program to go to two different directions.
The using try-catch instead of if-else you really should not use them interchangeably.
try/catch clause is used for things that goes wrong that are outside of your control and not in the normal program flow. For example, trying to write to a file and the file system is full? That situation should typically be handled with try/catch.
if-else clause should be used in normal flow and ordinary error checking. So, for example, user fails to populate a required input field? Use if for that, not try/catch.
In java, you use the try-catch statement when your code has a chance of throwing a exception which will need to be handed. The logic in the try-catchis ran until a exception is found where the logic moves to the catch box where you can handle the exception.
try{
//Exception prone logic
}catch(Exception e){
//handle the exception here
}
The if-else statement is a conditional statement which evaluates a boolean expression which directs the flow of the program either into the if-block of code or the else-block of code
if(i == 0){
//i is equal to 0
}else{
//i is not equal to 0
}
I was wondering what is the proper convention for handling a try/catch block. It is pretty obvious what should be within the try block but what about the catch block?
Can I write a message to the user like the following:
do {
try {
System.out.println("Pi to the number of decimal places:");
Scanner in = new Scanner(System.in);
userNth = in.nextInt();
} catch (Exception e) {
System.out.println("Error: Enter a number between 1 and 100");
}
} while(userNth < 1 || userNth > piDecimals);
Or is this bad practice?
Exception-handling is not the place to make rash assumptions; usually by the time this part of your code has been executed it's because something unanticipated has happened, this is when you want to be most careful to be accurate about detecting and recording what happened so that you can tell what needs fixing.
The choice of Exception as the type of exception that gets caught is too broad. The method you're calling throws 3 different exceptions for distinctly different reasons; only one of which is something that should be caught here. Also unchecked exceptions like NullPointerException will get caught by this. If you were to add some code to this catch block that inadvertently introduced a NPE it would be hard to figure out what went wrong. Your overbroad catch can result in bugs not being found or errors not getting handled properly.
(Btw Makoto makes a good point that nextInt isn't what you should be calling here anyway.)
Not logging the exception can be acceptable in narrow cases where you're certain of what the exception means (for instance, if you caught InputMismatchException, or NumberFormatException in Makoto's example code). But in combination with catching Exception it has the capacity to hide errors and cause confusion.
You likely chose to catch Exception because handling a bunch of different checked exceptions, most of which seemed unlikely to ever happen anyway, seemed like an intolerable nuisance. Providing a consistent way of handling and logging exceptions will help, by providing a reasonable default case for exceptions you don't know what to do with. That way if you see an exception you just can't handle, you always have the option of letting it be thrown (possibly catching it and wrapping it in an unchecked exception), knowing that if thrown it will get logged and end your program.
For a very small command-line program sometimes it's entirely ok to let exceptions that you can't handle be thrown from main (by adding throws Exception to the main method). This is ok for toy examples, small school projects, etc.; I'd only use it in production code if there was a plan for logging the output (like a batch file that redirects stderr to a file):
public static void main(String... args) throws Exception {
... application code
}
In most cases all the main method code should be placed in a try block where any Throwable is caught and logged:
public static void main(String... args) {
try {
... application code here
}
catch (Throwable t) {
logger.log(t);
}
}
Either alternative makes it less tempting for you to inappropriately swallow inconvenient checked exceptions.
Simple Answer: what you wrote is fine
Longer Answer: try-catch blocks are for executing code that may throw an exception, and then handling said exception if it occurs. In general, the catch block should have code that handles the exception however you need to handle it. If the statement you currently have is how you want to respond to an exception, then it's fine by convention. Some common things to do in a catch block are:
Throw another exception that encapsulates the thrown exception. (I often do this when parsing so that there can be a single ParseException)
Throw a runtime exception encapsulating the thrown exception and let java's default uncaught exception handler deal with it. (I do this a lot when I'm writing quick temporary programs and I don't want to deal with checked exceptions)
Pass it to some generic handler in your program, such as a GUI to display the error, etc.
call printStacktrace on it
But anything that fits your exception-handling needs is fine
In all actuality, this code is not going to function the way you intend it to. There are two key reasons for this:
nextInt() blocks until it receives an integer; that is, it's not going to care about what input you give it until it reads an integer, and
Even if this were to be okay, depending on how you initialize userNth and piDecimals, one or both of those variables may not be defined, thus preventing compilation.
Also, don't catch Exception. Be as specific as you can when catching exceptions, since Exception also includes some nifty and dangerous RuntimeExceptions like NullPointerException.
What you're looking to do:
Take in an integer input
If the user enters a non-integer, tell them they need to enter an integer
Keep doing this while userNth < 1 || userNth > piDecimals.
To that, we should look to get the right exception thrown by parsing the input as a string first, then as an Integer:
try {
System.out.println("Pi to the number of decimal places:");
userNth = Integer.parseInt(in.nextLine());
} catch (NumberFormatException e) {
System.out.println("Error: Enter a number between 1 and 100");
// You have to set this value to something so that userNth is defined!
userNth = Integer.MAX_VALUE;
}
The other part to this is that you have to decide what message you show if userNth > 1 && userNth < piDecimals, since your try...catch isn't going to cover that. This, I leave as an exercise for the reader.
I have a method throws an Exception
public int myMethod throws Exception
I have another function calls myMethod function and hava try-catch block.
I throws a runtime exception to enforce the program to be terminated.
Is this a proper way to terminate the program? If I do this way, it prints the stack trace twice and the stack trace from RuntimeException is useless.
What is the suggested way to terminate program in catch clause with printing the full stack trace.
public int callMyMethod(){
try{
myMethod();
}
catch(Exception ex){
ex.printStackTrace(System.out);
throw new RuntimeException();
}
}
The answer is "it depends".
If this code is part of the application itself then calling System.exit(int) is possibly the best option. (But if the application is "failing", then you should call exit with a non-zero return code. Zero conventionally means "succeeded".)
However, if there is a significant possibility that this code is going to be embedded / reused in a larger Java application, calling System.exit(...) is problematic. For instance a library that calls System.exit(...) when something bad happens is going to cause havoc for an application that uses it.
For something like that, you might throw a custom runtime exception which you catch and handle specifically in your main method. (If I was doing that, I'd pass the Exception as a constructor parameter to the custom exception ... and make it the cause exception. And I wouldn't print it / log it at that point.)
(Calling System.exit(...) also causes problems when you are unit testing ... 'cos the call will most likely pull the plug on the JVM running the test suite!)
The other point is that catch (Exception ...) is almost always a BAD IDEA. The point is that this catches just about everything (including all sorts of things that you never dreamed could happen!) and buries them. It is far better to catch the specific exceptions you are expecting (e.g. checked exceptions) and can deal with ... and just let the rest propagate in the normal way.
If you are stuck with catch (Exception ...) because you are using something that is declared as throwing Exception, the best way to deal with it is to change the throws Exception. And the sooner the better. Change the throws Exception to declare a list of (more) specific exceptions that you expect to be thrown by the method.
public int callMyMethod(){
try{
myMethod();
}
catch(Exception ex){
ex.printStackTrace(System.out);
System.exit(0); // terminates with exit code 0, no extra stack trace.
}
}
Exception handling is one of the most important aspects in programming.
The answer for your question depends on what type of application you are working on.
system.exit(0) will just terminate your program and this can create a lot of havoc .
Also make sure that you never catch Exception , if you are doing that then you are catching all the types of exceptions which you may not intend to handle also.
Always catch Specific exception such that it gives you opportunity to handle it in a manner which you need.
This question already has answers here:
Is a finally block without a catch block a java anti-pattern?
(12 answers)
Closed 9 years ago.
What is the best practice in using Try Catch Finally block? Do you prefer to use only try finally block and not try catch block? I always thought that try catch finally is the best practice to use. However, in part of the code I am working with I have seen code like this:
try{
doSomething();
}
finally{
doSomethingElse();
}
Since they don't catch the exception it was really hard for me to debug the code. It wasn't a really good practice to me not using catch and only finally, but I might be wrong.
To best of my understanding, this is not really a good practice. Basically, we are not making use of what try catch was intended to be used for. I have found similar questions as well.
My questions is: "Do you agree with me on the following hypothesis: The best practice is to use try catch finally together and not try finally." If you do not agree, would you please provide me with an example of when to use try finally instead of try catch finally and why you think try finally is better than try catch?
I disagree, if you cannot do anything about an exception being thrown, but something further up your caller hierarchy can, then use the finally to clean up your resources and let the caller deal with cleaning up after the exception is thrown.
The purpose of the finally construct is to provide code that will always execute, even if an exception is thrown.
The try / finally (no catch) allows you to write code that is guaranteed to execute even if a runtime exception is thrown by the code inside the try block.
This is good in situations where you are using code that might throw runtime exceptions but does not throw checked exceptions. An example of this is Spring DAO support; which wraps IOExceptions in runtime exceptions.
Generally try-finally is used to assure that some piece of code gets executed irrespective if the exception occurs or not.
Catch block is generally missing because code in try block does not throw any checked exception which can be caught.
Eg:
try {
if(str.length() > 0) { // If str is null, it can throw NullPointer and hence code below it wont execute
// some code
}
}finally {
// Will be performed even if any unchecked exception is thrown
// Must contain code which has to be performed at any cost like releasing occupied memory
}
There are three possibilities, try+catch, try+finally, or try+catch+finally. They all have their uses.
Use the catch with try when there's something you can usefully do to handle the exception, such as report the fact that the exception has occurred.
The code inside the finally block always runs, independent of whether an exception occurs or not, so use finally with try when there's cleaning up to do that's always got to happen. An example would be closing a file if it's been successfully opened.
I do not agree.
try{}finally{} should be used in cases where you cannot handle the exception, but are required to clean up resources.
A try{}finally{} block will not cause the exception to "disappear" as you seem to think it will. It will be thrown up the stack and be handled somewhere else. If you are unable to see the exception in your current application it's because it's being thrown away elsewhere.
try {
connection = createConnection();
}
finally {
closeConnection(connection) //Free database connection.
}
In this case, you may not have any ability to handle an SQL exception, but you still want to free the database connection.
I've been seeing code like this every now and then in PHP and I was wondering what's this all about.
$pdo = new PDO ($connect_string, $user, $pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
$pdo->exec ("QUERY WITH SYNTAX ERROR");
}
catch (PDOException $e) {
echo $e->getMessage();
}
What I'm interested is the catch (PDOException $e) code in general.
I var_dump the exception and it returns the PDOException class ( doh.. logical ). But that doesn't clear things what's the idea behind this technique, why it's used and what's it's name :)
I've seen this technique in Java programming also but unfortunately I don't know Java very well... :/
That is an exception handler to handle exceptions that have been thrown by $pdo->exec().
When you execute $pdo->exec(), there are possible exceptions (the code not being to function as desired) that can occur, and they are thrown (with throw new PDOException('error!') or similiar). They will be thrown as far as the first catch of their specific type.
In the example above, your catch() { ... } block will catch exceptions of PDOException. If you didn't have that block, it will bubble up to any further exception handlers, and if not handled, will crash your application. You will see some applications that have a try{ ... }/catch(){ ... } block wrapping their main request, so unhandled exceptions will bubble all the way up to it (and be handled).
If you need to have clean up code or any code that must be ran in the event of the exception being caught, you could use finally { ... } (but PHP at this stage does not support it).
If you want to change the behaviour of the exception handler, you can use set_exception_handler().
It's an error handling mechanism. If something goes wrong, an exception is thrown (in this case the exception's class is called PDOException) and in the catch part of the code you deal with the error message and possible cleaning of mess that might have occurred in try block.
you definetly should know something about OOP :)
This is the object oriented way of managing errors: in PHP (as in Java) unexpected situation (e.g. errors) are objects, exactly as anything else.
When a method (name it methodA() ) call cause some unexpected situation, instead of returning false or just terminating the program an "exception is thrown". That means that the method is interrupted, the program flow is passed to the method/function that called the "methodA()" method which have two options: thowing itself the exception or managing it.
Tha catch keywork stands for the second way: When you write some code that can maybe cause unexpected behaviour you can surround this code with a "try-catch" block, just like the example above: if the method call throw an exception object (of the type inside the catch clause) all the remaining code in the "try" block will be skipped and the code in the "catch" block will be executed. The remaining code will be executed as normal.
If you don't catch the exception you can run in different behaviour: in PHP it depends on your php.ini file, in JAVA it cause the program to end, in jsp the exception is shown in the screen and so on. Actually, in a production application you should ALWAYS catch exception when they may be thrown unless you're absolutely shure no exception will be raised.
just as a starting point have a look at this: http://php.net/manual/en/language.exceptions.php