Q : How to resume code operation after a handled exception ?
i now using try and catch.
Try
{
Process url and render the text and save contents to text file.
}Catch(Exception ex)
}
Some urls are broken, so how do i skip broken urls and continue with other urls ?
Depends on how you iterate over your URLs. For example:
for (URL url: urllist) {
try {
// Process **one** url
} catch (Exception ex) {
// handle the exception
}
}
This will process all urls in the list, even if some of the processing raises an exception.
That's it - do nothing (apart from perhaps logging a warning), and the code execution will continue. Ex:
for (String url : urls) {
try {
// parse, open, save, etc.
} catch (Exception ex) {
log.warn("Problem loading URL " + url, ex);
}
}
Try this:
for (url : allUrls) {
try {
Process url and render the text and save contents to text file.
} catch(Exception ex) {
...
continue;
}
}
There is a logical error in this pseudo-code.
Think about it like this. Your 'process url' was a loop yes? When it found an exception it exited the process loop to the catch block and then to the end of the algorithm.
You need to nest the entire try catch block in the process loop. That way when it hits an exception it returns to the begging of the loop and not to the end of the program.
Create two methods like this:
public void processAllURLs(final List<String> urls){
for(String url: urls){
processURL(url);
}
}
public void processURL(final String url){
try {
// Attempt to process the URL
} catch (Exception ex) {
// Log or ignore
}
}
Related
my program crash when user inserts a weird url
It should go like
while(condition) {
try {
String url = reciveURL();
Document rss = Jsoup.connect( url ).get();
}
catch (MalformedURLException e) {
System.err.println("Invalid URL");
} catch (OthersExceptions e){
Others.Actions();
}
}
The problem is, this throws "java.net.MalformedURLException: no protocol", instead of printing "Invalid URL" and the program crash (when user inserts any other kind of text)
Thanks!
Lol, solved myself, but i'll let the question as theres no post on the same issue
You should import java.net.url, this brings the "URL" type, which triggers the MalformedURLException (Jsoup doesnt do this)
So it goes like this
while(true){
{
String url = reciveURL() ;
URL chk_url = new URL(url);
Document rss = Jsoup.connect( url ).get();
} catch (MalformedURLException e) {
System.err.println("url mal puesta!");
}
}
I trying to check if an URL which I want to connect to exists or not. Here's my attempt:
try {
// Connect to the url
document = Jsoup.connect("http://www.malformedurl.com").get();
tags = document.select(".tags .tag a");
num = document.select(".tag .count");
// Take the wanted data
UrlFunctions.UrlParse(tags, num);
} catch (java.net.MalformedURLException e) {
System.out.println("URL DOESNT EXIST");
}
After running that, I don't get the message URL DOESNT EXIST. What exception should I use or what else should I do?
A MalFormedURLException will only be thrown when the URL is really malformed, i.e. it does not conform the URL spec, not when it does not exist. This is under the covers been thrown by the constructor of the java.net.URL class. Its javadoc tells the following:
throws
MalformedURLException - If the string specifies an unknown protocol.
So, it will only be thrown when you use for example "www.malformedurl.com" or
"foo://www.malformedurl.com" instead of "http://www.malformedurl.com".
To detect whether an URL exists you'd better to head for a different solution. If the host name is unknown, then you should catch UnknownHostException instead:
try {
document = Jsoup.connect("http://www.malformedurl.com").get();
// ...
} catch (UnknownHostException e) {
System.err.println("Unknown host");
e.printStackTrace(); // I'd rather (re)throw it though.
}
This is not necessarily a problem of the other end, it can also occur when the DNS server on your network is bogus.
Or, to detect whether an IP address is reachable, then you should catch SocketTimeoutException instead:
try {
document = Jsoup.connect("http://12.34.56.78").get();
// ...
} catch (SocketTimeoutException e) {
System.err.println("IP cannot be reached");
e.printStackTrace(); // I'd rather (re)throw it though.
}
I test exceptions using in java an dobjective-C programs.
In these tests, I see a difference in the way of finally block is reached when an exception is catched and rethrown.
Here my java test :
try {
Boolean bThrow = true;
System.out.println("try : before exception sent");
if (bThrow) {
throw new Exception();
}
System.out.println("try : after sent");
}
catch (Exception e) {
System.out.println("catch, rethrow");
throw e;
}
finally {
System.out.println("finally");
}
which displays :
try: before exception sent
catch, rethrow
finally
And here my objective-c test :
#try {
NSException *myexc = [NSException exceptionWithName:#"exceptionTest" reason:#"exceptionTest" userInfo:nil];
BOOL bThrow = YES;
NSLog(#"try : before exception sent");
if (bThrow) {
#throw myexc;
}
NSLog(#"try : after sent");
}
#catch (Exception *exception) {
NSLog(#"catch, rethrow");
#throw exception;
}
#finally {
NSLog(#"finally");
}
which displays :
try: before exception sent
catch, rethrown
*** Terminating app
Code in finally block is not reached !
Why this difference ?
[EDIT] Sorry, #try ... #try ... #try... was a mistake.
I changed it, but the problem is the same, i can't reach finally block in objective-c test
Your Objective-C code does not have a finally block, just three try blocks. It should look like this:
#try {
NSException *myexc = [NSException exceptionWithName:#"exceptionTest" reason:#"exceptionTest" userInfo:nil];
BOOL bThrow = YES; // Use BOOL or bool
NSLog(#"try : before exception sent");
if (bThrow) {
#throw myexc;
}
NSLog(#"try : after sent");
}
#catch (NSException *e) { // use catch not another try
NSLog(#"catch, rethrow");
#throw e;
}
#finally { // use finally not another try
NSLog(#"finally");
}
OK, i solved my problem.
In my objective-c test, application crashed, that's why finally block was not reached.
If I add a try catch block in the main, now in my function, finally block is reached !
So, I confirm that finally block is still reached whatever an excpetion occurs (and is rethrown) or not).
Just came across a rather confusing exam question, and my lecturer is away on holidays, so I come to StackOverflow begging for help!
The question is as follows :
"Joe has his own JoeConnection class for making connections between his computer and other computers. The class provides the following constructor and instance methods :
JoeConnection( String address ): Make a connection with the URL address.
void writeLn( String text ) : Write text to the JoeConnection.
String readLn( ): Read a line of text from the JoeConnection.
void clode( ) : Close the JoeConnection.
Joe's connections regularly fail and this causes errors. Using proper exception handling, demonstrate how to use Joe's JoeConnection class to
make a JoeConnection with the URL http://students.chat.box
write "Hello world" to the JoeConnection
read in a string from the JoeConnection
close the connection.
The connection handling should provide as man details as possible about the cause of failure and print the stack trace which led to the failure.
I have no idea how to tackle this, but I assume it is something similar to this :
public class Test {
try {
JoeConnection connection = new JoeConnection(http://students.chat.box);
} catch {
connectionError e; printStacktrace();}
}
}
Can anyone please help me figure this out? Thanks a lot.
Without an indication of what exceptions are thrown and why, the only proper exception handling is no handling at all. Don't catch an exception if you don't know how to fix the problem that triggered it.
But the further instructions in your assignment introduce a different notion of "proper." You're supposed to print a stack trace. So catch the exception and print a stack trace. You were on the right track, but your syntax was wrong. Refer back to your textbook and lecture notes to remind yourself what the syntax is for catching exceptions (and for passing strings to functions, for that matter).
try {
JoeConnection connection = new JoeConnection("http://students.chat.box");
connection.writeLn("Hello world");
// etc
} catch (Exception e) {
e.printStackTrace();
}
"Proper exception handling" is a little vague. I agree with #Rob Kennedy's statement that no exception handling is appropriate unless you know why the exception is thrown and what should be done with it. Otherwise, the exception should be allowed to propagate. So, for example:
void foo(String address) throws JoeException {
JoeConnection connection = new JoeConnection(address);
try {
connection.writeLn("Hello World!");
} finally {
// Ensure the connection is closed when finished.
// This happens whether an exception occurs or not.
connection.close();
}
}
If you wanted to catch the exception just to print it, you could do something like this:
void foo(String address) throws JoeException {
try {
JoeConnection connection = new JoeConnection(address);
try {
connection.writeLn("Hello World!");
} finally {
connection.close();
}
} catch (JoeException e) {
e.printStackTrace();
// Don't know what to do about this; rethrow.
throw e;
}
}
There is a subtlety here that even experience Java programmers can miss, though. If an exception occurs while creating the connection, it doesn't need to be closed. If an exception occurs while writing to the connection, it does need to be closed; thus the finally clause. However, the act of closing can also throw an exception. If closing the connection throws an exception, only that exception will be thrown by the try statement. If the finally clause was reached as a result of the writeLn operation throwing an exception, the exception of the writeLn call will be effectively ignored. This is probably not what you want.
Instead, we can try something ugly like this:
void foo(String address) throws JoeException {
try {
JoeConnection connection = new JoeConnection(address);
boolean normalCompletion = false;
try {
connection.writeLn("Hello World!");
normalCompletion = true;
} finally {
if (normalCompletion) {
// The writeLn operation completed normally.
// Propagate an exception thrown by the close operation.
connection.close();
} else {
// The writeLn operation completed abruptly.
// Ignore an exception thrown by the close operation.
try {
connection.close();
} catch (JoeException e) {
/* empty */
}
}
}
} catch (JoeException e) {
e.printStackTrace();
// Don't know what to do about this; rethrow.
throw e;
}
}
This looks (and is) syntactically hideous, but it does show "proper" exception handling of a sort. The language enhancement from Project Coin should clean this up a bit.
For starters, I can help you out with the syntax of what you wrote:
try {
JoeConnection connection = new JoeConnection("http://students.chat.box");
}
catch (JoeConnectionException e) {
e.printStacktrace();
}
I took the liberty of changing the linebreaks and renaming 'connectionError' as JoeConnectionException which looks more conventional to me.
You'll have to do something similar for the readLn, writeLn, and close method calls since it said that the connection regularly fails (i.e. not just while connecting).
Cheers, good luck.
Catching an exception should look like:
try {
JoeConnection conn = new JoeConnection(url);
} catch (YourExceptionClassNameHere e) {
e.printStackTrace();
}
Also: if you want to use a literal String, make sure you include the quotations. (It should be "http://students.chat.box".)
It's good to have a finally as well:
public class Test {
try {
JoeConnection connection = new JoeConnection(http://students.chat.box);
}
catch(Exception e) {
e.printStacktrace();
}
finally {
if(connection != null) {
connection.close();
}
}
}
Typically you handle exceptions if you know what to do with them (this involves error-recovery logic or wrapping an exception and throwing it to a higher level).
Assuming that each method throws an exception, you could do something like this for "maximum detail":
public class Test {
JoeConnection connection = null;
try {
connection = new JoeConnection("http://students.chat.box");
...
...
}
catch(OpenException e) {
System.out.println("Error while opening connection");
e.printStacktrace();
}
catch(WriteException e) {
System.out.println("Error while writing to connection");
e.printStacktrace();
}
catch(ReadException e) {
System.out.println("Error while reading from connection");
e.printStacktrace();
}
finally {
if(connection != null) {
connection.close();
}
}
}
Is there an elegant way to handle exceptions that are thrown in finally block?
For example:
try {
// Use the resource.
}
catch( Exception ex ) {
// Problem with the resource.
}
finally {
try{
resource.close();
}
catch( Exception ex ) {
// Could not close the resource?
}
}
How do you avoid the try/catch in the finally block?
I usually do it like this:
try {
// Use the resource.
} catch( Exception ex ) {
// Problem with the resource.
} finally {
// Put away the resource.
closeQuietly( resource );
}
Elsewhere:
protected void closeQuietly( Resource resource ) {
try {
if (resource != null) {
resource.close();
}
} catch( Exception ex ) {
log( "Exception during Resource.close()", ex );
}
}
I typically use one of the closeQuietly methods in org.apache.commons.io.IOUtils:
public static void closeQuietly(OutputStream output) {
try {
if (output != null) {
output.close();
}
} catch (IOException ioe) {
// ignore
}
}
If you're using Java 7, and resource implements AutoClosable, you can do this (using InputStream as an example):
try (InputStream resource = getInputStream()) {
// Use the resource.
}
catch( Exception ex ) {
// Problem with the resource.
}
Arguably a bit over the top, but maybe useful if you're letting exceptions bubble up and you can't log anything from within your method (e.g. because it's a library and you'd rather let the calling code handle exceptions and logging):
Resource resource = null;
boolean isSuccess = false;
try {
resource = Resource.create();
resource.use();
// Following line will only run if nothing above threw an exception.
isSuccess = true;
} finally {
if (resource != null) {
if (isSuccess) {
// let close throw the exception so it isn't swallowed.
resource.close();
} else {
try {
resource.close();
} catch (ResourceException ignore) {
// Just swallow this one because you don't want it
// to replace the one that came first (thrown above).
}
}
}
}
UPDATE: I looked into this a bit more and found a great blog post from someone who has clearly thought about this more than me: http://illegalargumentexception.blogspot.com/2008/10/java-how-not-to-make-mess-of-stream.html He goes one step further and combines the two exceptions into one, which I could see being useful in some cases.
As of Java 7 you no longer need to explicitly close resources in a finally block instead you can use try-with-resources syntax. The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.
Assume the following code:
try( Connection con = null;
Statement stmt = con.createStatement();
Result rs= stmt.executeQuery(QUERY);)
{
count = rs.getInt(1);
}
If any exception happens the close method will be called on each of these three resources in opposite order in which they were created. It means the close method would be called first for ResultSetm then the Statement and at the end for the Connection object.
It's also important to know that any exceptions that occur when the close methods is automatically called are suppressed. These suppressed exceptions can be retrieved by getsuppressed() method defined in the Throwable class.
Source: https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
Ignoring exceptions which occur in a 'finally' block is generally a bad idea unless one knows what those exceptions will be and what conditions they will represent. In the normal try/finally usage pattern, the try block places things into a state the outside code won't be expecting, and the finally block restores those things' state to what the outside code expects. Outside code which catches an exception will generally expect that, despite the exception, everything has been restored to a normal state. For example, suppose some code starts a transaction and then tries to add two records; the "finally" block performs a "rollback if not committed" operation. A caller might be prepared for an exception to occur during the execution of the second "add" operation, and may expect that if it catches such an exception, the database will be in the state it was before either operation was attempted. If, however, a second exception occurs during the rollback, bad things could happen if the caller makes any assumptions about the database state. The rollback failure represents a major crisis--one which should not be caught by code expecting a mere "Failed to add record" exception.
My personal inclination would be to have a finally method catch exceptions that occur and wrap them in a "CleanupFailedException", recognizing that such failure represents a major problem and such an exception should not be caught lightly.
One solution, if the two Exceptions are two different classes
try {
...
}
catch(package1.Exception err)
{
...
}
catch(package2.Exception err)
{
...
}
finally
{
}
But sometimes you cannot avoid this second try-catch. e.g. for closing a stream
InputStream in=null;
try
{
in= new FileInputStream("File.txt");
(..)// do something that might throw an exception during the analysis of the file, e.g. a SQL error
}
catch(SQLException err)
{
//handle exception
}
finally
{
//at the end, we close the file
if(in!=null) try { in.close();} catch(IOException err) { /* ignore */ }
}
Why do you want to avoid the additional block? Since the finally block contains "normal" operations which may throw an exception AND you want the finally block to run completely you HAVE to catch exceptions.
If you don't expect the finally block to throw an exception and you don't know how to handle the exception anyway (you would just dump stack trace) let the exception bubble up the call stack (remove the try-catch from the finally block).
If you want to reduce typing you could implement a "global" outer try-catch block, which will catch all exceptions thrown in finally blocks:
try {
try {
...
} catch (Exception ex) {
...
} finally {
...
}
try {
...
} catch (Exception ex) {
...
} finally {
...
}
try {
...
} catch (Exception ex) {
...
} finally {
...
}
} catch (Exception ex) {
...
}
After lots of consideration, I find the following code best:
MyResource resource = null;
try {
resource = new MyResource();
resource.doSomethingFancy();
resource.close();
resource = null;
} finally {
closeQuietly(resource)
}
void closeQuietly(MyResource a) {
if (a!=null)
try {
a.close();
} catch (Exception e) {
//ignore
}
}
That code guarantees following:
The resource is freed when the code finished
Exceptions thrown when closing the resource are not consumed without processing them.
The code does not try to close the resource twice, no unnecessary exception will be created.
If you can you should test to avoid the error condition to begin with.
try{...}
catch(NullArgumentException nae){...}
finally
{
//or if resource had some useful function that tells you its open use that
if (resource != null)
{
resource.Close();
resource = null;//just to be explicit about it was closed
}
}
Also you should probably only be catching exceptions that you can recover from, if you can't recover then let it propagate to the top level of your program. If you can't test for an error condition that you will have to surround your code with a try catch block like you already have done (although I would recommend still catching specific, expected errors).
You could refactor this into another method ...
public void RealDoSuff()
{
try
{ DoStuff(); }
catch
{ // resource.close failed or something really weird is going on
// like an OutOfMemoryException
}
}
private void DoStuff()
{
try
{}
catch
{
}
finally
{
if (resource != null)
{
resource.close();
}
}
}
I usually do this:
MyResource r = null;
try {
// use resource
} finally {
if( r != null ) try {
r.close();
} catch( ThatSpecificExceptionOnClose teoc ){}
}
Rationale: If I'm done with the resource and the only problem I have is closing it, there is not much I can do about it. It doesn't make sense either to kill the whole thread if I'm done with the resource anyway.
This is one of the cases when at least for me, it is safe to ignore that checked exception.
To this day I haven't had any problem using this idiom.
try {
final Resource resource = acquire();
try {
use(resource);
} finally {
resource.release();
}
} catch (ResourceException exx) {
... sensible code ...
}
Job done. No null tests. Single catch, include acquire and release exceptions. Of course you can use the Execute Around idiom and only have to write it once for each resource type.
Changing Resource from best answer to Closeable
Streams implements Closeable Thus you can reuse the method for all streams
protected void closeQuietly(Closeable resource) {
if (resource == null)
return;
try {
resource.close();
} catch (IOException e) {
//log the exception
}
}
I encountered a situation similar where I couldn't use try with resources but I also wanted to handle the exception coming from the close, not just log and ignore it like closeQuietly mechanism do. in my case I'm not actually dealing with an output stream, so the failure on close is of more interest than a simple stream.
IOException ioException = null;
try {
outputStream.write("Something");
outputStream.flush();
} catch (IOException e) {
throw new ExportException("Unable to write to response stream", e);
}
finally {
try {
outputStream.close();
} catch (IOException e) {
ioException = e;
}
}
if (ioException != null) {
throw new ExportException("Unable to close outputstream", ioException);
}