Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 2

Practical No.

23, 24 & 25
Program Code: Demonstrates exception handling using try, catch, and
finally block.
class Exception{

public static void main(String args[]){

int a,b,c;

try{

a = Integer.parseInt(args[0]);

b = Integer.parseInt(args[1]);

c = a/b;

System.out.println("Division is: "+c);

catch (ArithmeticException e){

System.out.println("Can't divided by zero");

finally {

a = Integer.parseInt(args[0]);

b = Integer.parseInt(args[1]);

c = a+b;

System.out.println("Addition is: "+c);

}}}

Practical related question:


3. Can we throw exception manually? Illustrate with sample program
Yes, we can throw an exception manually in Java using throw keyword.
public class ExceptionExample {

public static void main(String[] args) {

try {

throw new Exception("Manually throwing an exception!");

} catch (Exception e) {

System.out.println("Caught exception: " + e.getMessage());


}}}

Exercise:
1. The program calculates sum of two numbers inputted as
command-line arguments. When will it give an exception?
class excep{

public static void main(String args[])

try {

int n=Integer.parseInt(args[0]);

int n1=Integer.parseInt(args[1]);

int n2=n+n1;

System.out.println("Sum is:"+n2);

catch(NumberFormatException ex){

System.out.println(ex);

} finally {

System.out.println("You inputted a correct integer number");

}}}

2. Develop a program to accept a password from the user and throw


"Authentication Failure" exception if the password is incorrect.

3. Write the exception thrown by the following code block?


Integer[][] ints={(1, 2, 3), (null), (7,8,9)):
System.out.println("value="+ints[1][1].intValue());
The following code block will throw a NullPointerException exception

You might also like