Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignoring exceptions

I have some code which ignores a specific exception.

try
{
    foreach (FileInfo fi in di.GetFiles())
    {
        collection.Add(fi.Name);
    }
    foreach (DirectoryInfo d in di.GetDirectories())
    {
        populateItems(collection, d);
    }
}
catch (UnauthorizedAccessException ex)
{
   //ignore and move onto next directory
}

of course this results in a compile time warning as ex is unused. Is there some standard accept noop which should be used to remove this warning?

like image 334
stimms Avatar asked Oct 24 '08 02:10

stimms


People also ask

What is exception ignored?

When the exception happens and the catch block above is executed, nothing will be done by Java. The exception is ignored and the next line of code below the catch block will be executed as if nothing has happened.

Can we ignore exception?

To ignore an exception in Java, you need to add the try... catch block to the code that can throw an exception, but you don't need to write anything inside the catch block. Let's see an example of how to do this. In your main() method, you can surround the call to the checkAge() method with a try...

What happens if exceptions are not properly handled?

if you don't handle exceptions When an exception occurred, if you don't handle it, the program terminates abruptly and the code past the line that caused the exception will not get executed.

What are the 3 types of exceptions?

There are three types of exception—the checked exception, the error and the runtime exception.


2 Answers

Just rewrite it as

catch (UnauthorizedAccessException) {}
like image 197
tvanfosson Avatar answered Sep 19 '22 00:09

tvanfosson


As Dave M. and tvanfosson said, you want to rewrite it as

catch (UnauthorizedAccessException) {}

The bigger question that should be asked, however, is why you are catching an exception on ignoring it (commonly called swallowing the exception)? This is generally a bad idea as it can (and usually does) hide problems in the application at runtime that can lead to very strange results and a difficult time debugging them.

like image 42
Scott Dorman Avatar answered Sep 20 '22 00:09

Scott Dorman