How to make a Simple Java Code to Throw an Exception

Java programming topics
Post Reply
User avatar
Nipuna
Moderator
Moderator
Posts: 2729
Joined: Mon Jan 04, 2010 8:02 pm
Location: Deraniyagala,SRI LANKA

How to make a Simple Java Code to Throw an Exception

Post by Nipuna » Tue May 03, 2011 10:49 am

Hello

I am reading Head First Java Book

And Now I am at Exception Handling Chapter. I want to know a little Simple code that throws an Exception.

I like to see 2 Codes with throw keyword and without keyword.

Because I am bit confused in that chapter that's why i need simple codes to examine. :?


Thanks
User avatar
Neo
Site Admin
Site Admin
Posts: 2642
Joined: Wed Jul 15, 2009 2:07 am
Location: Colombo

Re: How to make a Simple Java Code to Throw an Exception

Post by Neo » Tue May 03, 2011 4:29 pm

First of all, it is required for you learn the meaning of exception handling and why it is required.

An exception is an indication of a problem that occurs during a program's execution. The name "exception" implies that the problem occurs infrequently-if the "rule" is that a statement normally executes correctly, then the "exception to the rule" is that a problem occurs. Exception handling enables programmers to create applications that can resolve (or handle) exceptions. In many cases, handling an exception allows a program to continue executing as if no problem had been encountered. A more severe problem could prevent a program from continuing normal execution, instead requiring it to notify the user of the problem before terminating in a controlled manner. Exception handling enables programmers to write robust and fault-tolerant programs (i.e., programs that are able to deal with problems that may arise and continue executing).

Now lets move on to a common mathematical error with division, the 'divide by zero'. In mathematics, if we divide a number by zero, we define the result is infinity. However, computers are finite machines. That means computers always must work with specified limits defined by numerical data types such as byte, short, int, long, float, double, etc...

If you try something like a = 5000/0; in Java without Exception Handling, you will get a run time error as below. Your program will no longer work and exit to command prompt. (Note that line numbers in the error message will be changed according to the line which the error occurs).

Code: Select all

Exception in thread "main" java.lang.ArithmeticException: / by zero
        at DivideByZeroNoExceptionHandling.quotient(
           DivideByZeroNoExceptionHandling.java:10)
        at DivideByZeroNoExceptionHandling.main(
           DivideByZeroNoExceptionHandling.java:22)
So you understand that when an Exception such as 'divide by zero' occurs, your program will no longer continue it's normal operation and will exit to command prompt or shell.

As the above description about Exception Handling states, if we code the risky lines within a specific error handling region, then we can detect that and control the behaviour.

If we have the values defined by us at the time of coding, we could avoid 'divide by zero'. How if we ask the user to enter two values and then outputs the result. We have no control what the user will enter to the two values.

Code: Select all

import java.util.Scanner;

public class MyClass
{

	public static int quotient( int numerator, int denominator )
	{
		return numerator / denominator; // possible division by zero
	} // end method quotient

	public static void main( String args[] )
	{
		Scanner scanner = new Scanner( System.in ); // scanner for input
		int numerator, denominator, result;

		System.out.print( "Please enter an integer numerator: " );
		numerator = scanner.nextInt();
		System.out.print( "Please enter an integer denominator: " );
		denominator = scanner.nextInt();

		result = quotient( numerator, denominator );
		
		System.out.printf( "\nResult: %d / %d = %d\n", numerator, denominator, result);
	}
}
Consider following 3 entries.
  1. Code: Select all

    Please enter an integer numerator: 50
    Please enter an integer denominator: 10
     
    Result: 50 / 10 = 5
    
    No errors
  2. Code: Select all

    Please enter an integer numerator: 10
    Please enter an integer denominator: 0
    Exception in thread "main" java.lang.ArithmeticException: / by zero
            at DivideByZeroNoExceptionHandling.quotient(
               DivideByZeroNoExceptionHandling.java:10)
            at DivideByZeroNoExceptionHandling.main(
               DivideByZeroNoExceptionHandling.java:22)
    

    Arithmetic Exception: / by zero
  3. Code: Select all

    Please enter an integer numerator: 10
    Please enter an integer denominator: robot.lk
    Exception in thread "main" java.util.InputMismatchException
            at java.util.Scanner.throwFor(Unknown Source)
            at java.util.Scanner.next(Unknown Source)
            at java.util.Scanner.nextInt(Unknown Source)
            at java.util.Scanner.nextInt(Unknown Source)
            at DivideByZeroNoExceptionHandling.main(
               DivideByZeroNoExceptionHandling.java:20)
    
    Input Mismatch exception

You are now clear about the errors that may occur due to invalid user behaviours. There is a nice way in Java where we can detect the problem and inform the user about the error in entry and ask him to re-enter some valid numbers. Here is how we do it.

Code: Select all

import java.util.InputMismatchException;
import java.util.Scanner;

public class MyClass
{
	// demonstrates throwing an exception when a divide-by-zero occurs
	public static int quotient( int numerator, int denominator ) throws ArithmeticException
	{
		return numerator / denominator; // possible division by zero
	} // end method quotient

	public static void main( String args[] )
	{
		Scanner scanner = new Scanner( System.in ); // scanner for input
		boolean continueLoop = true; // determines if more input is needed
		int numerator, denominator, result;

		do
		{
			try // read two numbers and calculate quotient
			{
				System.out.print( "Please enter an integer numerator: " );
				numerator = scanner.nextInt();
				System.out.print( "Please enter an integer denominator: " );
				denominator = scanner.nextInt();

				result = quotient( numerator, denominator );
				System.out.printf( "\nResult: %d / %d = %d\n", numerator, denominator, result );
				continueLoop = false; // input successful; end looping
			} // end try
			catch ( InputMismatchException e1)
			{
				System.err.printf( "\nException: %s\n", e1);
				scanner.nextLine(); // discard input so user can try again
				System.out.println("You must enter integers. Please try again.\n" );
			} // end catch
			catch ( ArithmeticException e2)
			{
				System.err.printf( "\nException: %s\n", e2);
				System.out.println("Zero is an invalid denominator. Please try again.\n" );
			} // end catch
			
		} while ( continueLoop ); // end do...while
		
	} // end main
	
} // end class MyClass
Note that the risky code is now protected with a 'try' block and the possible exception are handled with 'catch' blocks.

Here are some sample operations with this program.
  1. Code: Select all

    Please enter an integer numerator: 50
    Please enter an integer denominator: 10
    
    Result: 50 / 10 = 5
    No error
  2. Code: Select all

    Please enter an integer numerator: 10
    Please enter an integer denominator: 0
    
    Exception: java.lang.ArithmeticException: / by zero
    Zero is an invalid denominator. Please try again.
    
    Please enter an integer numerator: 100
    Please enter an integer denominator: 50
    
    Result: 100 / 50 = 2
    Divide by zero found but detected correctly
  3. Code: Select all

    Please enter an integer numerator: 100
    Please enter an integer denominator: robot.lk
    
    Exception: java.util.InputMismatchException
    You must enter integers. Please try again.
    
    Please enter an integer numerator: 10
    Please enter an integer denominator: 2
    
    Result: 10 / 2 = 5
    Input Mismatch found but detected correctly
User avatar
Nipuna
Moderator
Moderator
Posts: 2729
Joined: Mon Jan 04, 2010 8:02 pm
Location: Deraniyagala,SRI LANKA

Re: How to make a Simple Java Code to Throw an Exception

Post by Nipuna » Tue May 03, 2011 5:53 pm

Thanks Friend Now I have Some Understanding.

By Coding More I'll get Full Understanding.


Thanks for Helping Me while doing your busy works.
Post Reply

Return to “Java Programming”