+ Reply to Thread
Results 1 to 7 of 7

Thread: Handling Exceptions

  1. #1
    whitey6993's Avatar
    whitey6993 is offline Programming Expert
    Join Date
    Dec 2008
    Posts
    435
    Rep Power
    15

    Handling Exceptions

    This tutorial is meant to serve as a basic introduction to handling errors and exceptions in Java using such techniques as try-catch blocks and assertions. Before tackling this tutorial, you should have a firm grasp on the basic concepts of Java. Please enjoy the tutorial.

    Most of us have dealt with the problem of errors or exceptions at some point in our programming experience. Enter the wrong data type, or even data that is unexpected such as a number that is to big, and your whole program crashes. However, there are some simple techniques that you can use to "catch" that unexpected data and deal with it in a more organized manor than your program outputting some incomprehensible error message.

    Lets say you have a piece of code that sums up some numbers, for example:
    Code:
    //Some code
    double sum = 0;
    for(int i = 0; i < arguments.length; i++) //for every argument, add it
    	sum += arguments[i];
    System.out.println(sum);
    //Some code
    This is pretty straight forward. In this code fragment, you take some numbers as arguments to the program and total the sum of the numbers using a for loop. This works fine if all the input consists of is numbers. But lets say one of your users decides they're going to get mischievous on you and input a character like so:
    Code:
    SumNumbers 0 5 2 5 x
    Now your program exits with some odd error message that scares your user half-to-death (this is an exaggeration, it probably won't scare them that much). There is a simple solution to this problem. All we have to do is modify the code like so:
    Code:
    //Some code
    double sum = 0;
    for(int i = 0; i < arguments.length; i++)
    {
    	try
    	{
    		sum += arguments[i];
    	} catch (NumberFormatException e)
    	{
    		System.out.println("Non-number input: " + argument[i]);
    	}
    }
    System.out.println(sum);
    //Some code
    What we did here is add in something called a "try-catch" block. Try-catch blocks allow your program to catch errors and handle them in a way that you specify. You can use try-catch blocks for a number of more complex purposes than the one shown in this program. For example, maybe instead of just outputting the error you might want to convert the string to a number. Or even ask the user to input the correct number in place of your current number.

    Try-catch blocks can also be used to catch multiple errors by simply using different catch blocks for every type of exception you want to handle. This is done like so:
    Code:
    try
    {
    	//Some code to try
    } catch (NumberFormatException e)
    {
    	//Handle number format exceptions
    } catch (ArithmaticException e)
    {
    	//Handle arithmetic exceptions
    }
    This way, you can handle pretty much any type of error that your encounter. Also, a word about exception types. There are many different types of exception types specified by Java. All have different cases in which they are used. If you want to handle any exception with a generic response, however, simply use a block like this:
    Code:
    try
    {
    	//Some code
    } catch (Exception e)
    {
    	//Catch any exception
    }
    All exceptions inherit from the exception class, so this statement will catch any exception. There is one more thing that you can do in try-catch blocks called a finally statement. Finally statements execute no matter what and are placed at the end of your try-catch block. For instance, here is a generic try-catch-finally block:
    Code:
    try
    {
    	//Try some code here
    } catch (Exception e)
    {
    	//Catch any exceptions here
    } finally
    {
    	//Do this statement no matter what
    }
    There is another weapon available to Java developers in the eternal battle against errors and exceptions. The "assert" statement allows programmers to setup a checkpoint in their software to make sure their variables are on track and have the right value. Assert statements are basically Boolean if statements that allow you to check a condition and output an error message if it is not true.

    For example, lets say you just wrote some software to maintain inner workings of a nuclear energy plant. It might be a good idea to let the folks working there know if the temperature gets to hot so they can have a little time to evacuate before it explodes huh? Well, the assert statment makes this easy. Take a look at the following code.
    Code:
    //Code that manages the power plant
    assert temperature <= 4000 : "She's gonna blow! Run for the hills!";
    This statement just checks to make sure that the temperature is at or below 4000 and if it isn't, it outputs a friendly error message to the workers.

    This tutorial should serve as a basic introduction to some techniques for handling errors and exceptions in programs. It is by no means a comprehensive guide for handling errors, but shows some basic techniques that can be easily implemented in any program. Feed back is greatly appreciated, and if you have any questions or would like to contribute to the content posted here, please post a reply. Thank You .

  2. CODECALL Circuit advertisement
    Join Date
    Always
    Posts
    Many

     
  3. #2
    Deadlock's Avatar
    Deadlock is offline Learning Programmer
    Join Date
    Mar 2010
    Location
    Egypt
    Posts
    81
    Rep Power
    7

    Re: Handling Exceptions

    Defensive programming is a must when receiving inputs or dealing with networks. Great tutorial.

  4. #3
    Auxcil's Avatar
    Auxcil is offline Newbie
    Join Date
    Mar 2010
    Location
    Illinois, USA
    Posts
    23
    Blog Entries
    1
    Rep Power
    0

    Re: Handling Exceptions

    I always hate starting a new programming language because they don't teach Error handling soon enough or long enough. Great Tut, this info is a necessity for a great program.

  5. #4
    whitey6993's Avatar
    whitey6993 is offline Programming Expert
    Join Date
    Dec 2008
    Posts
    435
    Rep Power
    15

    Re: Handling Exceptions

    Thank you

  6. #5
    javaman is offline Newbie
    Join Date
    Apr 2010
    Posts
    12
    Rep Power
    0

    Re: Handling Exceptions

    Hi,
    nice tutorial.

    are there any alternatives for error handling in Java?
    i'm just reading on error handling. like in c++, i'm meeting such things as retturn codes, deferred error handling.i haven't gone into much details on these. but are they available in java?

  7. #6
    GMVResources's Avatar
    GMVResources is offline Learning Programmer
    Join Date
    Jun 2010
    Posts
    72
    Rep Power
    0

    Re: Handling Exceptions

    Hey, nice tutorial! Good job for error handling.

  8. #7
    GMVResources's Avatar
    GMVResources is offline Learning Programmer
    Join Date
    Jun 2010
    Posts
    72
    Rep Power
    0

    Re: Handling Exceptions

    javaman this is basically it, the try catch and finally block.

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Similar Threads

  1. MVC vs ActionListener vs Exceptions
    By Shaddix in forum Java Help
    Replies: 3
    Last Post: 04-05-2010, 11:37 AM
  2. Exceptions in Java and PL/SQL
    By olvitar in forum Java Help
    Replies: 2
    Last Post: 03-30-2010, 11:28 PM
  3. Debugging exceptions
    By Shaddix in forum Visual Basic Programming
    Replies: 1
    Last Post: 12-28-2009, 03:50 PM
  4. Application exceptions
    By smithcarvo in forum ASP, ASP.NET and Coldfusion
    Replies: 1
    Last Post: 09-08-2008, 12:05 PM
  5. Re-throwing Exceptions? I don't understand
    By thieflock in forum Java Help
    Replies: 1
    Last Post: 02-20-2008, 12:11 PM

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts