0% found this document useful (0 votes)
4 views

Exception Handling in Java

The document demonstrates handling exceptions in Java programs. It shows compile-time and runtime errors, and how to use try-catch blocks to handle exceptions like array index out of bounds and division by zero errors at runtime.

Uploaded by

Aruna Nishad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Exception Handling in Java

The document demonstrates handling exceptions in Java programs. It shows compile-time and runtime errors, and how to use try-catch blocks to handle exceptions like array index out of bounds and division by zero errors at runtime.

Uploaded by

Aruna Nishad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

Demonstration 10: Exceptional Handling

/* 1. Showing compile time error in a program. */

/* 2. Showing run-time errors in a program. */

class demo102
{
public static void main(String args[])
{
int a= Integer.parseInt(args[0]);
int b= Integer.parseInt(args[1]);
int c=a/b;
System.out.println("Value of c =" + c);
}
}

/* Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1(or


0) out of bounds for length 1(or 0) */
/* Exception in thread "main" java.lang.NumberFormatException: For input string:
"5.5" */

/* 3. Run the following program without exception-handling */


public class Demo103
{
static int function(int x, int y)
{
int a=x/y;
return a;
}
public static void main(String args[])
{
int a,b,result;
a=0;
b=0;
System.out.println("Enter any two integers");
a=Integer.parseInt(args[0]);
b=Integer.parseInt(args[1]);
result=function(a,b);
System.out.println("Result : " + result);
}
}

/* Exception in thread "main" java.lang.ArithmeticException: / by zero at


Demo103.function(Demo103.java:5)
*/

/* Run the following program with exception handling mechanism */

//Case : Simple try-catch block...

public class Demo104


{
static int function(int x, int y)
{
try
{
int a=x/y;
return a;
}
catch (ArithmeticException e)
{
System.out.println ("Division by zero" );
}
return 0;
}
public static void main(String args[])
{
int a,b,result;
a=0;
b=0;
System.out.println("Enter any two integers");
try{
a=Integer.parseInt(args[0]);
b=Integer.parseInt(args[1]);
}
catch(Exception e)
{}
result=function(a,b);
System.out.println("Result : " + result);
}
}

You might also like