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
How to make a Simple Java Code to Throw an Exception
Re: How to make a Simple Java Code to Throw an Exception
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).
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.
Consider following 3 entries.
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.
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.
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)
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);
}
}
-
No errors
Code: Select all
Please enter an integer numerator: 50 Please enter an integer denominator: 10 Result: 50 / 10 = 5
-
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 -
Input Mismatch exception
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)
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
Here are some sample operations with this program.
-
No error
Code: Select all
Please enter an integer numerator: 50 Please enter an integer denominator: 10 Result: 50 / 10 = 5
-
Divide by zero found but detected correctly
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
-
Input Mismatch found but detected correctly
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
Re: How to make a Simple Java Code to Throw an Exception
Thanks Friend Now I have Some Understanding.
By Coding More I'll get Full Understanding.
Thanks for Helping Me while doing your busy works.
By Coding More I'll get Full Understanding.
Thanks for Helping Me while doing your busy works.