
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Multiple Try Blocks with One Catch Block in Java
An exception is an issue (run time error) occurred during the execution of a program. When an exception occurred the program gets terminated abruptly and, the code past the line that generated the exception never gets executed.
Example
import java.util.Scanner; public class ExceptionExample { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.println("Enter first number: "); int a = sc.nextInt(); System.out.println("Enter second number: "); int b = sc.nextInt(); int c = a/b; System.out.println("The result is: "+c); } }
Output
Enter first number: 100 Enter second number: 0 Exception in thread "main" java.lang.ArithmeticException: / by zero at ExceptionExample.main(ExceptionExample.java:10)
Multiple try blocks:
You cannot have multiple try blocks with a single catch block. Each try block must be followed by catch or finally. Still if you try to have single catch block for multiple try blocks a compile time error is generated.
Example
The following Java program tries to employ single catch block for multiple try blocks.
class ExceptionExample{ public static void main(String args[]) { int a,b; try { a=Integer.parseInt(args[0]); b=Integer.parseInt(args[1]); } try { int c=a/b; System.out.println(c); }catch(Exception ex) { System.out.println("Please pass the args while running the program"); } } }
Compile time exception
ExceptionExample.java:4: error: 'try' without 'catch', 'finally' or resource declarations try { ^ 1 error
Advertisements