This is a Java program to handle the Exception using Try and Multiple Catch Block.
A Java exception is an error condition that has occurred in a piece of code on violation of some rules.
Java Exception Handling is managed via five keywords: try, catch, throw, throws, and finally.
Here is the source code of the Java Program to Handle the Exception Using Try and Multiple Catch Block. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.
import java.io.FileInputStream;
import java.util.Scanner;
public class Try_Catch
{
public static void main(String[] args)
{
int a=5,b=0,c,d,f;
try
{
Scanner s=new Scanner(System.in);
System.out.print("Enter a:");
a=s.nextInt();
System.out.print("Enter b:");
b=s.nextInt();
System.out.print("Enter c:");
c=s.nextInt();
d=a/b;
System.out.println(d);
f=a%c;
System.out.println(f);
FileInputStream fis = null;
/*This constructor FileInputStream(File filename)
* throws FileNotFoundException which is a checked
* exception*/
fis = new FileInputStream("B:/myfile.txt");
int k;
/*Method read() of FileInputStream class also throws
* a checked exception: IOException*/
while(( k = fis.read() ) != -1)
{
System.out.print((char)k);
}
/*The method close() closes the file input stream
* It throws IOException*/
fis.close();
}
catch(IndexOutOfBoundsException e)
{
System.out.println(e);
}
catch(NullPointerException e)
{
System.out.println(e);
}
catch(ArithmeticException e)
{
System.out.println(e);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Output:
$ javac Try_Catch.java $ java Try_Catch Enter a:4 Enter b:5 Enter c:6 0 4 java.io.FileNotFoundException: B:/myfile.txt (No such file or directory)
Sanfoundry Global Education & Learning Series – 1000 Java Programs.
advertisement
Here’s the list of Best Books in Java Programming, Data Structures and Algorithms.
Related Posts:
- Apply for Java Internship
- Practice BCA MCQs
- Check Java Books
- Practice Programming MCQs
- Apply for Computer Science Internship