vasanth0989 / prep-myself

0 stars 0 forks source link

Exceptions, try, catch, finally and Errors #5

Open vasanth0989 opened 10 months ago

vasanth0989 commented 10 months ago

Exceptions

Exceptions:
 description: 
 - Any abnormal in executing your program, example - NullPointerException
 - Exceptions can be recovered, you can recover from an exception using try, catch and finally block
 - IndexOutOfBound is an Exception
 types:
  - CheckedException | CompileTimeException:
    description:
     - Example are - IOException, say a method is throwing exception, the caller of the method needs to handle the exception.
     - Either they can rethrow it, they can hanlde it via try and catch block
     - If you are not doing either of this, meaning not handling using try/catch or not defined 'throws' in the method signature your code won't compile.
  - UnCheckedException | RunTimeException :
    - As the name denotes these type of exception only occur during Runtime
    - Examples are 'NullPointerException', 'IndexOutOfBoundException'
    - You don't need to handle this exception using 'try/catch' or declaring 'throws' inside method signature, your code will happily compile.

Errors:
 description:
  - You cannot recover, it's outside our control, example would be 'OutofMemoryError'

finally:
 description:
  - 'finally' block, will be added after 'try&catch' or it can be added just to the 'try' block
  - Just before your 'method return statement' the finally block gets executed.
  - Finally will always gets executed even if Exception occurs or not.
vasanth0989 commented 10 months ago
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class LearningException {

    public static void main(String[] args) {
        // Example for Null Pointer Exception (Unchecked / RunTimeException)
//        Employee employee = null;
//        checkForId(employee);
//        writeFileWithTryCatch("sample.txt");
//        try {
//            writeFileWithThrows("sample.txt");
//        } catch (IOException ex) {
//            ex.printStackTrace();
//        }
//        writeFileWithTryCatchUsingThrow("sample.txt");
//        System.out.println("Done writing");

        Employee employee = new Employee(123, "Test");
        checkForId(employee);
        System.out.println("This will not get printed");

    }

    static boolean checkForId(Employee employee) {
        if (employee != null) {
            // custom Business validation
            // We have req, where to check if ID is 123 we have to throw an Exception
            // you can throw - checked Exception
            // you can throw - unchecked | RunTime exception
            if(employee.getId() == 123) {
                throw new RuntimeException("This employee is Flagged we cannot allow him to access!!");
            }
            return employee.getId() > 100;
        }
        return false;
    }

    static void writeFileWithTryCatch(String fileName) {
        BufferedWriter writer = null;
        // multiple try/catch
        try {
            // Constructor chaining
            writer = new BufferedWriter(new FileWriter(fileName));
            writer.write("Hello, this is a test file!\n");
            writer.write("This is another line of text.");

        }
        // while catching exception the hierarchy has to be followed
        // The child class would come first
        // the parent 'Exception' would be always last in the chain
        // We are just swallowing the Exception meaning we are not throwing back the exception
        // If an Exception occurs it just stops right here in this method only it will not be delegated to this method callers.
        catch (IOException ex) {
            System.out.println("Error occurred while writing to the file");
            ex.printStackTrace();
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            try {
                writer.close();
            } catch (IOException e) {
            }
        }
    }

    static void writeFileWithTryCatchUsingThrow(String fileName) throws Exception {
        BufferedWriter writer = null;
        // multiple try/catch
        try {
            // Constructor chaining
            writer = new BufferedWriter(new FileWriter(fileName));
            writer.write("Hello, this is a test file!\n");
            writer.write("This is another line of text.");

        }
        // while catching exception the hierarchy has to be followed
        // The child class would come first
        // the parent 'Exception' would be always last in the chain
        // Let's not swallow this instead we will throw an Exception
        catch (IOException ex) {
            System.out.println("Error occurred while writing to the file");
            ex.printStackTrace();
            // throwing new Exception
//            throw new IOException();
            // throwing the same Exception
            // We are manually throwing an Exception
            throw ex;
        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        } finally {
            try {
                writer.close();
            } catch (IOException e) {
            }
        }
    }

    static void writeFileWithThrows(String fileName) throws IOException {
        BufferedWriter writer = new BufferedWriter(new FileWriter(fileName));
        writer.write("Hello, this is a test file! from throws!!!\n");
        writer.write("This is another line of text.");
        writer.close();
    }
}

class Employee {
    private int id;
    private String name;

    public Employee(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public Employee() {
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}
vasanth0989 commented 10 months ago

using 'finally' block

import java.util.ArrayList;
import java.util.List;

public class TestMain {

    public static void main(String[] args) {
        List<Account> accounts = new ArrayList<>();
        accounts.add(new Account(1, "CHK"));
        accounts.add(new Account(2, "SVG"));
        System.out.println("The total number of iterations is:" + getNumberOfIterations(accounts));
    }

    static int getNumberOfIterations(List<Account> accounts) {
        int count = 0;
        try {
            for (Account account : accounts) {
                count += 1;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        // This will always run even if it is success or failure
        finally {
            count = 999;
        }
        return count;
    }
}

class Account {
    private int id;
    private String type;

    public Account() {
    }

    public Account(int id, String type) {
        this.id = id;
        this.type = type;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", type='" + type + '\'' +
                '}';
    }
}