

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Try, catch, throw and throws in Java
Try and catch in Java
A method catches an exception using a combination of the try and catch keywords. A try/catch block is placed around the code that might generate an exception.
Following is the syntax for try and catch −
try { // Protected code } catch (ExceptionName e1) { // Catch block }
A catch statement involves declaring the type of exception you are trying to catch. If an exception occurs in protected code, the catch block (or blocks) that follows the try is checked. If the type of exception that occurred is listed in a catch block, the exception is passed to the catch block much as an argument is passed into a method parameter.
Example
Let us now see an example to implement try and catch −
import java.io.*; public class Demo { public static void main(String args[]) { try { int a[] = new int[5]; System.out.println("Access element eighth :" + a[7]); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Exception thrown :" + e); } System.out.println("Out of the block"); } }
Output
Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 7 Out of the block
throw and throws in Java
If a method does not handle a checked exception, the method must declare it using the throws keyword. The throws keyword appears at the end of a method's signature.
You can throw an exception, either a newly instantiated one or an exception that you just caught, by using the throw keyword.
The throws is used to postpone the handling of a checked exception and throw is used to invoke an exception explicitly.
- Related Questions & Answers
- Throw and throws in Java
- Try/catch/finally/throw keywords in C#
- Difference between throw and throws in Java
- Can we declare a try catch block within another try catch block in Java?
- What is the difference between throw and throws keywords in Java?
- Flow control in try catch finally in Java
- Try-Catch-Finally in C#
- What are try, catch, finally blocks in Java?
- What is the difference between throw e and throw new Exception(e) in catch block in java?
- Flow control in a try catch finally in Java
- Flow control in try catch finally in Java programming.
- Explain try and catch statements in JavaScript with examples.
- Can a try block have multiple catch blocks in Java?
- Can we write any statements between try, catch and finally blocks in Java?
- Explain Try/Catch/Finally block in PowerShell