Built-In Exceptions:
Within given example you see how the automatic exceptions in Java work. This application creates a function and forces it to divide by zero. A method does not have to explicitly throw an exception since the division operator throws an exception when needed.
// a built-in exception.
import java.io.* ;
import java.lang.Exception ;
public class DivideBy0 {
public static void main( String[] args ) {
int a = 2 ;
int b = 3 ;
int c = 5 ;
int d = 0 ;
int e = 1 ;
int f = 3 ;
try
{
System.out.println( a+"/"+b+" = "+div( a, b ) ) ;
System.out.println( c+"/"+d+" = "+div( c, d ) ) ;
System.out.println( e+"/"+f+" = "+div( e, f ) ) ;
}
catch( Exception except )
{
System.out.println( "Caught exception " +
except.getMessage() ) ;
}
}
static int div( int a, int b ) {
return (a/b) ;
}
}
The output of given application is displays here:
2/3 = 0
Caught exception / by zero
The first call to div () works better. The second call fails since of the divide-by-zero error. Even by the application did not specify it, an exception was thrown-and caught. Then you could use arithmetic within your code without writing code which explicitly checks bounds.