0% found this document useful (0 votes)
2 views8 pages

Exception Programs

The document provides various examples of exception handling in Java, including try...catch, try...finally, and nested try blocks. It also explains the use of the throws keyword for declaring exceptions and when to prefer it over traditional try/catch blocks. Additionally, it discusses throwing unchecked exceptions and handling multiple exceptions using the throws keyword.

Uploaded by

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

Exception Programs

The document provides various examples of exception handling in Java, including try...catch, try...finally, and nested try blocks. It also explains the use of the throws keyword for declaring exceptions and when to prefer it over traditional try/catch blocks. Additionally, it discusses throwing unchecked exceptions and handling multiple exceptions using the throws keyword.

Uploaded by

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

Example: Java try...

catch block
class Main {
public static void main(String[] args) {

try {
int divideByZero = 5 / 0;
[Link]("Rest of code in try block");
}

catch (ArithmeticException e) {
[Link]("ArithmeticException => " + [Link]());
}
}
}
Example: Java try...finally block
class Main {
public static void main(String[] args) {
try {
int divideByZero = 5 / 0;
}

finally {
[Link]("Finally block is always executed");
}
}
}
Java try...catch...finally block
import [Link].*;

class ListOfNumbers {

// create an integer array


private int[] list = {5, 6, 8, 9, 2};

// method to write data from array to a fila


public void writeList() {
PrintWriter out = null;
try {
[Link]("Entering try statement");

// creating a new file [Link]


out = new PrintWriter(new FileWriter("[Link]"));

// writing values from list array to [Link]


for (int i = 0; i < 7; i++) {
[Link]("Value at: " + i + " = " + list[i]);
}
}

catch (Exception e) {
[Link]("Exception => " + [Link]());
}

finally {
// checking if PrintWriter has been opened
if (out != null) {
[Link]("Closing PrintWriter");
// close PrintWriter
[Link]();
}

else {
[Link]("PrintWriter not open");
}
}

}
}

class Main {
public static void main(String[] args) {
ListOfNumbers list = new ListOfNumbers();
[Link]();
}
}
Multiple Catch blocks
class ListOfNumbers {
public int[] arr = new int[10];

public void writeList() {

try {
arr[10] = 11;
}

catch (NumberFormatException e1) {


[Link]("NumberFormatException => " + [Link]());
}

catch (IndexOutOfBoundsException e2) {


[Link]("IndexOutOfBoundsException => " + [Link]());
}

}
}

class Main {
public static void main(String[] args) {
ListOfNumbers list = new ListOfNumbers();
[Link]();
}
}
Syntax of Nested try Catch
class NestingDemo{
public static void main(String args[]){
//main try-block
try{
//try-block2
try{
//try-block3
try{
int arr[]= {1,2,3,4};
/* I'm trying to display the value of
* an element which doesn't exist. The
* code should throw an exception
*/
[Link](arr[10]);
}catch(ArithmeticException e){
[Link]("Arithmetic Exception");
[Link](" handled in try-block3");
}
}
catch(ArithmeticException e){
[Link]("Arithmetic Exception");
[Link](" handled in try-block2");
}
}
catch(ArithmeticException e3){
[Link]("Arithmetic Exception");
[Link](" handled in main try-block");
}
catch(ArrayIndexOutOfBoundsException e4){
[Link]("ArrayIndexOutOfBoundsException");
[Link](" handled in main try-block");
}
catch(Exception e5){
[Link]("Exception");
[Link](" handled in main try-block");
}
}
}
Output:

ArrayIndexOutOfBoundsException handled in main try-block


As you can see that the ArrayIndexOutOfBoundsException occurred in the
grand child try-block3. Since try-block3 is not handling this exception, the
control then gets transferred to the parent try-block2 and looked for the catch
handlers in try-block2. Since the try-block2 is also not handling that exception,
the control gets transferred to the main (grand parent) try-block where it found
the appropriate catch block for exception. This is how the the nesting structure
works.

Example 2: Nested try block


class Nest{
public static void main(String args[]){
//Parent try block
try{
//Child try block1
try{
[Link]("Inside block1");
int b =45/0;
[Link](b);
}
catch(ArithmeticException e1){
[Link]("Exception: e1");
}
//Child try block2
try{
[Link]("Inside block2");
int b =45/0;
[Link](b);
}
catch(ArrayIndexOutOfBoundsException e2){
[Link]("Exception: e2");
}
[Link]("Just other statement");
}
catch(ArithmeticException e3){
[Link]("Arithmetic Exception");
[Link]("Inside parent try catch block");
}
catch(ArrayIndexOutOfBoundsException e4){
[Link]("ArrayIndexOutOfBoundsException");
[Link]("Inside parent try catch block");
}
catch(Exception e5){
[Link]("Exception");
[Link]("Inside parent try catch block");
}
[Link]("Next statement..");
}
}

Example : Throwing Unchecked Exception

public class TestThrow1 {


//function to check if person is eligible to vote or not
public static void validate(int age) {
if(age<18) {
//throw Arithmetic exception if not eligible to vote
throw new ArithmeticException("Person is not eligible to v
ote");
}
else {
[Link]("Person is eligible to vote!!");
}
}
//main method
public static void main(String args[]){
//calling the function
validate(13);
[Link]("rest of the code...");
}
}

Throws:
In simple words, the throws keyword is used to declare the exception. It
gives an indication to the developer about the exception that may
occur. It is better for the developer to provide the exception handling
code so that the normal flow of the program is maintained. There are
two ways to handle the code

Syntax of throws keyword


methodName(Arguments) throws
Exception1,Exception2,Exception3...{
//code
}

. Below is an example of a throws keyword in Java. In this example,


we are handling the IOException using the try/catch block in the main
method.

import [Link].*;
public class ThrowsExampleOne {
public static void main(String args[]) {
try {
fetchFile();
}
catch(IOException ex) {
[Link](ex);
}
}
// Below method throws IOException
public static void fetchFile() throws IOException{
//Below code can throw IOException
File file = new File("[Link]");
FileInputStream stream = new FileInputStream(file);
}
}
Example 2: declaring throws keyword in the main
method
2.1 In the below example, we are handling the exception by declaring
throws keyword in the main method. Since exception does not occur, the
code is executed fine.

import [Link].*;
public class ThrowsExampleTwo {
public static void main(String args[]) throws IOException{
fetchFile();
[Link]("Code will execute fine");
}
public static void fetchFile() throws IOException{
[Link]("This code is not throwing IOException");
}
}
Example 3 Throwing multiple exceptions using
throws keyword
In the below example, we are throwing multiple exceptions i.e
NullPointerException, InvalidClassException, IOException in the fetchFile()
method.

mport [Link].*;
public class ThrowsExampleFour {
public static void main(String args[]) {
try {
fetchFile();
}
catch(InvalidClassException ex1) {
[Link]([Link]());
}
catch(IOException ex2) {
[Link]([Link]());
}
}
public static void fetchFile() throws NullPointerException,
InvalidClassException,IOException {

// code that can throw IOException

When to use throws keyword over


try/catch/finally block
1. It is possible that there are several methods that can cause
exceptions. Writing try... catch block for each method will be difficult
as code becomes long and less-readable.
2. throws keyword can also be used when you have checked
exception that you do not want to handle it in the current method.

That's all for today, please mention in the comments in case you have
any questions related to throws keyword in Java with examples.

You might also like