User-defined Exceptions - Tutorialspoint | W3school

User-defined Exceptions

Now you can make your own java exceptions. Keep these points in your mind while writing your own exception classes.
All exceptions should be a child of Throwable
If you wish to write one checked exception which is automatically enforced by the declare or Handle Rule, you required to extend that exception class.
If it’s time to run runtime exception, then you require to extend the RuntimeException Class.

Look below to see how exception is defined below-

We can define our own Exception class as below −

class MyException extends Exception {
}

You are required to extend that predefined Exception class so to make your own Exception. These are known to be checked exceptions. InsfficientFundsException class is classified as a user-defined exception which extends the Exception class and make it a checked exception. Exception class contains more useful methods and fields.

Example

// File Name InsufficientFundsException.java
import java.io.*;
public class InsufficientFundsException extends Exception {
private double amount;
public InsufficientFundsException(double amount) {
this.amount = amount;
}
public double getAmount() {
return amount;
}
}

To show sing user-defined exception, the following checking Account contains a withdraw method which throws an InsufficientFundsException.

// File Name CheckingAccount.java
import java.io.*;
public class CheckingAccount {
private double balance;

private int number;
public CheckingAccount(int number) {
this.number = number;
}
public void deposit(double amount) {
balance
+= amount;
}
public void withdraw(double amount) throws InsufficientFundsException {
if(amount <= balance) {
balance
-= amount;
}else {
double needs = amount balance;
throw new InsufficientFundsException(needs);
}
}
public double getBalance() {
return balance;
}
public int getNumber() {
return number;
}
}

The following BankDemo program demonstrates invoking the deposit() and withdraw() methods of CheckingAccount.

// File Name BankDemo.java
public class BankDemo {
public static void main(String [] args) {
CheckingAccount c = new CheckingAccount(101);
System.out.println(“Depositing $500…”);
c
.deposit(500.00);
try {
System.out.println(“\nWithdrawing $100…”);
c
.withdraw(100.00);
System.out.println(“\nWithdrawing $600…”);
c
.withdraw(600.00);
}catch(InsufficientFundsException e) {
System.out.println(“Sorry, but you are short $” + e.getAmount());
e
.printStackTrace();
}
}
}

Join all the above mentioned three files and run BankDemo. This will gives the following output:

Output

Depositing $500…

Withdrawing $100…

Withdrawing $600…
Sorry, but you are short $200.0
InsufficientFundsException
at CheckingAccount.withdraw(CheckingAccount.java:25)
at BankDemo.main(BankDemo.java:13)

A finally block comes at the end of catch blocks and has this syntax −

Syntax

try {
// Protected code
}catch(ExceptionType1 e1) {
// Catch block
}catch(ExceptionType2 e2) {
// Catch block
}catch(ExceptionType3 e3) {
// Catch block
}finally {
// The finally block always executes.
}

Example

public class ExcepTest {

public static void main(String args[]) {
int a[] = new int[2];
try {
System.out.println(“Access element three :” + a[3]);
}catch(ArrayIndexOutOfBoundsException e) {
System.out.println(“Exception thrown :” + e);
}finally {
a[0] = 6;
System.out.println(“First element value: ” + a[0]);
System.out.println(“The finally statement is executed”);
}
}
}

This will produce the following result −

Output

Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3
First element value: 6
The finally statement is executed

Note the accompanying −

A catch clause can’t exist without an attempt statement

It is not necessary to have at last statements at whatever point an attempt/block square is available.

The attempt block can’t be available without either get condition or at long last provision.

Any code can’t be available in the middle of the attempt, get, at finally block..

The try-with resources:

For the most part, when we utilize any assets like streams, associations, and so on we need to close them unequivocally utilizing at long finally block. In the accompanying system, we are perusing information from a document utilizing FileReader and we are shutting it utilizing a finally block.

Example

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class ReadData_Demo {
public static void main(String args[]) {
FileReader fr = null;
try {
File file = new File(“file.txt”);
fr
= new FileReader(file); char [] a = new char[50];
fr
.read(a); // reads the content to the array
for(char c : a)
System.out.print(c); // prints the characters one by one
}catch(IOException e) {
e
.printStackTrace();
}finally {
try {
fr
.close();
}catch(IOException ex) {
ex
.printStackTrace();
}
}
}
}

Try with resources is also known as automatic resource management. It is a new managing mechanism that was bring in Java 7, and which automatically close all the resources utilised within the try catch block.

In order to use this statement first you are required to declare the needed resources within the parenthesis, and also the created resource that will get closed automatically at the corner of the block. Following isthe try with resources statement given syntax.

Syntax

try(FileReader fr = new FileReader(“file path”)) {
// use the resource
}catch() {
// body of catch
}
}

Given below is the program that reads the data of fil by making use of Try-with resources statement.

Example

import java.io.FileReader;
import java.io.IOException;
public class Try_withDemo {
public static void main(String args[]) {
try(FileReader fr = new FileReader(“E://file.txt”)) {
char [] a = new char[50];
fr
.read(a); // reads the contentto the array
for(char c : a)
System.out.print(c); // prints the characters one by one
}catch(IOException e) {
e
.printStackTrace();
}
}
}

These points should be kept in mind while working with try-with-resources statement.

To make use of class with try-with resources statement one should implement AutoCloseable interface as well as close() method of it to get invoked automatically in the meantime.

More than one class can be declared in try with resources statement.

When you declare more than two classes in try clock these classes are get closed in reverse order.

You have to expect the declaration of rosutin with the parenthesis everything is the similar as normal catch/try block of a block.

The resources declared at the try blocks that is at last declared as final.