- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Is it possible to have multiple try blocks with only 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
- Related Articles
- Can a try block have multiple catch blocks in Java?
- Can we define a try block with multiple catch blocks in Java?
- Is it possible to catch multiple Java exceptions in single catch block?
- Can we declare a try catch block within another try catch block in Java?
- Can we have a try block without a catch block in Java?\n
- What are try, catch, finally blocks in Java?
- Is it necessary that a try block should be followed by a catch block in Java?
- How to use Try/catch blocks in C#?
- PHP Exception Handling with Multiple catch blocks
- Explain Try/Catch/Finally block in PowerShell
- Can we write any statements between try, catch and finally blocks in Java?
- How to catch multiple exceptions in one line (except block) in Python?
- Can we have an empty catch block in Java?
- Exception Hierarchy in case of multiple catch blocks.
- What is the try block in Java?

Advertisements