0% found this document useful (0 votes)
6 views2 pages

Exception Handling in Java Programs

Uploaded by

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

Exception Handling in Java Programs

Uploaded by

stuffsharma69
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Assignment - 8

1. Write a program to implement the concept of Exception Handling using predefined exception.

Code : import [Link];


import [Link];
class Trump {
static void print(int arr[])throws IOException{
Scanner sc = new Scanner([Link]);
try {
[Link]("Please enter 10 values : ");
for(int i = 0 ; i < 10; i++) {
arr[i] = [Link]();
}
if(arr[0] >= 100) throw new IOException();
[Link]("Please enter 2 index to divide element at that Index : ");
int idx1 = [Link]();
int idx2 = [Link]();
int ans = arr[idx1]/arr[idx2];
[Link]("dividing element at index "+idx1+" by element at index "+idx2+"we get =
"+ans);

}
catch(ArrayIndexOutOfBoundsException e) {
[Link]("CATCHES OUT OF BOUNDS EXCEPTION " +e);
}
catch(ArithmeticException e) {
[Link]("CATCHES ARITHMETIC EXCEPTION " +e);
}
finally {
[Link]("finally will always be executed ");
}
[Link]("size of the array is = "+10);

}
}
public class print {
public static void main(String[] args) throws IOException{

Scanner sc = new Scanner([Link]);


int arr[] = new int[10];

[Link](arr);
}
}
output :
2. Write a program to implement the concept of Exception Handling by creating user defined
exceptions.
Code:
import [Link];
import [Link];
class MyException extends Exception {
public String toString() {
return "Wrong password";
}
}
class Checker {
static void check(String userName, int password) throws IOException {
try {
if ([Link]("admin") && password == 12345) {
[Link]("You are now logged in as: " +userName);
} else {
throw new MyException();
}
if (password > 12345) {
throw new IOException();
}
} catch (MyException e) {
[Link]("Please enter correct password: " + e);
} finally {
[Link]("Finally block always printed");
}
[Link]("Username = " + userName + ", Password = " +password);
}
}
public class ieh2 {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
String userName;
int password;
[Link]("Enter the Username: ");
userName = [Link]();
[Link]("Enter the Password: ");
password = [Link]();
try {
[Link](userName, password);
} catch (IOException e) {
[Link]("IO Exception occurred: " + e);
}
}
}
Output:

You might also like