EzDevInfo.com

error-handling interview questions

Top error-handling frequently asked interview questions

Should a retrieval method return 'null' or throw an exception when it can't produce the return value?

I have a method that is suppose to return an object if it is found.

If it is not found, should I:

  1. return null
  2. throw an exception
  3. other

Source: (StackOverflow)

Why is "except: pass" a bad programming practice?

I often see comments on other Stack Overflow questions about how the use of except: pass is discouraged. Why is this bad? Sometimes I just don't care what the errors, are and I want to just continue with the code.

try:
    something
except:
    pass

Why is using an except: pass block bad? What makes it bad? Is it the fact that I pass on an error or that I except any error?


Source: (StackOverflow)

Advertisements

What is the difference between exit() and abort()?

In C and C++, what is the difference between exit() and abort()? I am trying to end my program after an error (not an exception).


Source: (StackOverflow)

How can I exclude all "permission denied" messages from "find"?

I need to hide all permission denied messages from:

find . > files_and_folders

I am experimenting when such message arises. I need to gather all folders and files, to which it does not arise.

Is it possible to direct the permission levels to the files_and_folders file?

How can I hide the errors at the same time?


Source: (StackOverflow)

Begin, Rescue and Ensure in Ruby?

I've recently started programming in Ruby, and I am looking at exception handling.

I was wondering if ensure was the Ruby equivalent of finally in C#? Should I have:

file = File.open("myFile.txt", "w")

begin
  file << "#{content} \n"
rescue
  #handle the error here
ensure
  file.close unless file.nil?
end

or should I do this?

#store the file
file = File.open("myFile.txt", "w")

begin
  file << "#{content} \n"
  file.close
rescue
  #handle the error here
ensure
  file.close unless file.nil?
end

Does ensure get called no matter what, even if an exception isn't raised?


Source: (StackOverflow)

Can I try/catch a warning?

I need to catch some warnings being thrown from some php native functions and then handle them.

Specifically:

array dns_get_record  ( string $hostname  [, int $type= DNS_ANY  [, array &$authns  [, array &$addtl  ]]] )

It throws a warning when the DNS query fails.

try/catch doesn't work because a warning is not an exception.

I now have 2 options:

  1. set_error_handler seems like overkill because I have to use it to filter every warning in the page (is this true?);

  2. Adjust error reporting/display so these warnings don't get echoed to screen, then check the return value; if it's false, no records is found for hostname.

What's the best practice here?


Source: (StackOverflow)

Disabling Strict Standards in PHP 5.4

I'm currently running a site on php 5.4, prior to this I was running my site on 5.3.8. Unfortunately, php 5.4 combines E_ALL and E_STRICT, which means that my previous setting for error_reporting does not work now. My previous value was E_ALL & ~E_NOTICE & ~E_STRICT Should I just enable values one at a time?

I have far too many errors and the files contain too much code for me to fix.


Source: (StackOverflow)

How do I log ALL exceptions globally for a C# MVC4 WebAPI app?

Background

I am developing an API Service Layer for a client and I have been requested to catch and log all errors globally.

So, while something like an unknown endpoint (or action) is easily handled by using ELMAH or by adding something like this to the Global.asax:

protected void Application_Error()
{
     Exception unhandledException = Server.GetLastError();
     //do more stuff
}

. . .unhandled errors that are not related to routing do not get logged. For example:

public class ReportController : ApiController
{
    public int test()
    {
        var foo = Convert.ToInt32("a");//Will throw error but isn't logged!!
        return foo;
    }
}

I have also tried setting the [HandleError] attribute globally by registering this filter:

filters.Add(new HandleErrorAttribute());

But that also does not log all errors.

Problem/Question

How do I intercept errors like the one generated by calling /test above so that I can log them? It seems that this answer should be obvious, but I have tried everything I can think of so far.

Ideally, I want to add some things to the error logging, such as the IP address of the requesting user, date, time, and so forth. I also want to be able to e-mail the support staff automatically when an error is encountered. All of this I can do if only I can intercept these errors when they happen!

RESOLVED!

Thanks to Darin Dimitrov, whose answer I accepted, I got this figured out. WebAPI does not handle errors in the same way as a regular MVC controller.

Here is what worked:

1) Add a custom filter to your namespace:

public class ExceptionHandlingAttribute : ExceptionFilterAttribute
{
    public override void OnException(HttpActionExecutedContext context)
    {
        if (context.Exception is BusinessException)
        {
            throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
            {
                Content = new StringContent(context.Exception.Message),
                ReasonPhrase = "Exception"
            });

        }

        //Log Critical errors
        Debug.WriteLine(context.Exception);

        throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
        {
            Content = new StringContent("An error occurred, please try again or contact the administrator."),
            ReasonPhrase = "Critical Exception"
        });
    }
}

2) Now register the filter globally in the WebApiConfig class:

public static class WebApiConfig
{
     public static void Register(HttpConfiguration config)
     {
         config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{action}/{id}", new { id = RouteParameter.Optional });
         config.Filters.Add(new ExceptionHandlingAttribute());
     }
}

OR you can skip registration and just decorate a single controller with the [ExceptionHandling] attribute.


Source: (StackOverflow)

Cryptic "Script Error." reported in Javascript in Chrome and Firefox

I have a script that detects Javascript errors on my website and sends them to my backend for reporting. It reports the first error encountered, the supposed line number, and the time.

EDIT to include doctype:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" xmlns:fb="http://www.facebook.com/2008/fbml">

...

<script type="text/javascript">
//<![CDATA[
// for debugging javascript!
(function(window){
    window.onerror = function(msg, url, ln) {
        //transform errors
        if (typeof(msg) === 'object' && msg.srcElement && msg.target) {
            if(msg.srcElement == '[object HTMLScriptElement]' && msg.target == '[object HTMLScriptElement]'){
                msg = 'Error loading script';
            }else{
                msg = 'Event Error - target:' + msg.target + ' srcElement:' + msg.srcElement;
            }
        }

        msg = msg.toString();

        //ignore errors
        if(msg.indexOf("Location.toString") > -1){
            return;
        }
        if(msg.indexOf("Error loading script") > -1){
            return;
        }

        //report errors
        window.onerror = function(){};
        (new Image()).src = "/jserror.php?msg=" + encodeURIComponent(msg) + "&url=" + encodeURIComponent(url || document.location.toString().replace(/#.*$/, "")) + "&ln=" + parseInt(ln || 0) + "&r=" + (+new Date());
    };
})(window);
//]]>
</script>

Because of this script, I'm acutely aware of any javascript errors that are happening on my site. One of by biggest offenders is "Script Error." on line 0. in Chrome 10+, and Firefox 3+. This error doesn't exist (or may be called something else?) in Internet Explorer.

Correction (5/23/2013): This "Script Error, Line 0" error is now showing up in IE7 and possibly other versions of IE. Possibly a result of a recent IE security patch as this behavior previously did not exist.

Does anyone have any idea what this error means or what causes it? It happens on about 0.25% of my overall pageloads, and represents half the reported errors.


Source: (StackOverflow)

AsyncTask and error handling on Android

I'm converting my code from using Handler to AsyncTask. The latter is great at what it does - asynchronous updates and handling of results in the main UI thread. What's unclear to me is how to handle exceptions if something goes haywire in AsyncTask#doInBackground.

The way I do it is to have an error Handler and send messages to it. It works fine, but is it the "right" approach or is there better alternative?

Also I understand that if I define the error Handler as an Activity field, it should execute in the UI thread. However, sometimes (very unpredictably) I will get an Exception saying that code triggered from Handler#handleMessage is executing on the wrong thread. Should I initialize error Handler in Activity#onCreate instead? Placing runOnUiThread into Handler#handleMessage seems redundant but it executes very reliably.


Source: (StackOverflow)

Error handling in BASH

What is your favorite method to handle errors in BASH? The best example of handling errors in BASH I have found on the web was written by William Shotts, Jr at http://www.linuxcommand.org.

William Shotts, Jr suggests using the following function for error handling in BASH:

#!/bin/bash

# A slicker error handling routine

# I put a variable in my scripts named PROGNAME which
# holds the name of the program being run.  You can get this
# value from the first item on the command line ($0).

# Reference: This was copied from <http://www.linuxcommand.org/wss0150.php>

PROGNAME=$(basename $0)

function error_exit
{

#   ----------------------------------------------------------------
#   Function for exit due to fatal program error
#   	Accepts 1 argument:
#   		string containing descriptive error message
#   ----------------------------------------------------------------


    echo "${PROGNAME}: ${1:-"Unknown Error"}" 1>&2
    exit 1
}

# Example call of the error_exit function.  Note the inclusion
# of the LINENO environment variable.  It contains the current
# line number.

echo "Example of error with line number and message"
error_exit "$LINENO: An error has occurred."

Do you have a better error handling routine that you use in BASH scripts?


Source: (StackOverflow)

How to log errors and warnings into a file?

How to turn on all error and warnings and log them to a file but to set up all of that within the script (not changing anything in php.ini). I want to define a file name and so that all errors and warnings get logged into it.


Source: (StackOverflow)

Detailed 500 error message, ASP + IIS 7.5

IIS 7.5 , 2008rc2, classic asp, 500 error msg:

The page cannot be displayed because an internal server error has occurred.

I need to know how to configure IIS to get a more detailed error.
I've tried setting to true all of debugging options in the ASP configuration.
But that didn't work. Can anyone help me?


Source: (StackOverflow)

Catch all javascript errors and send them to server

I wondered if anyone had experience in handling javascript errors globally and send them from the client browser to a server.

I think my point is quite clear, i want to know every exception, error, compilation error, ... that happens on the client side and send them to the server to report them.

I'm mainly using mootools and head.js (for the js side) and django for the server side (not that it matters...).

Thank you for your help.

Regards.


Source: (StackOverflow)

Custom error pages on asp.net MVC3

I'm developing a MVC3 base website and I am looking for a solution for handling errors and Render custom Views for each kind of error. So imagine that I have a "Error" Controller where his main action is "Index" (generic error page) and this controller will have a couple more actions for the errors that may appear to the user like "Handle500" or "HandleActionNotFound".

So every error that may happen on the website may be handled by this "Error" Controller (examples: "Controller" or "Action" not found, 500, 404, dbException, etc).

I am using Sitemap file to define website paths (and not route).

This question was already answered, this is a reply to Gweebz

My final applicaiton_error method is the following:

protected void Application_Error() {
//while my project is running in debug mode
if (HttpContext.Current.IsDebuggingEnabled && WebConfigurationManager.AppSettings["EnableCustomErrorPage"].Equals("false"))
{
    Log.Logger.Error("unhandled exception: ", Server.GetLastError());
}
else
{
    try
    {
        var exception = Server.GetLastError();

        Log.Logger.Error("unhandled exception: ", exception);

        Response.Clear();
        Server.ClearError();
        var routeData = new RouteData();
        routeData.Values["controller"] = "Errors";
        routeData.Values["action"] = "General";
        routeData.Values["exception"] = exception;

        IController errorsController = new ErrorsController();
        var rc = new RequestContext(new HttpContextWrapper(Context), routeData);
        errorsController.Execute(rc);
    }
    catch (Exception e)
    {
        //if Error controller failed for same reason, we will display static HTML error page
        Log.Logger.Fatal("failed to display error page, fallback to HTML error: ", e);
        Response.TransmitFile("~/error.html");
    }
}
}

Source: (StackOverflow)