cs notebook0
  • Introduction
  • Core Java
  • some notes
  • Data structure&algorithm
  • Garbage Collection
  • HashMap
  • Collection0
  • Collection1
  • Collection2
  • comparatorVScomparable
  • exception0
  • exception1
  • exception2
  • Enum in Java
  • JVM
  • Wrapper Classes in Java
  • String, int convert
  • HashSetVSTreeSetVSLinkedHashSet
  • Pair
Powered by GitBook
On this page
  • 7. Java Exception propagation
  • 8. Java Throws keyword
  • 8.1 Syntax of java throws
  • 8.2 Which exception should be declared
  • 8.3 Advantage of Java throws keyword
  • 8.4 Java throws example
  • 9. Throw VS Throws
  • 10. Difference between final, finally and finalize
  • 11. ExceptionHandling with MethodOverriding in Java
  • 12. Java Custom Exception
  • 13. 3 Different ways to print Exception messages in Java
  • 13.1 java.lang.Throwable. printStackTrace() method:
  • 13.2 toString() method:
  • 13.3 java.lang.Throwable.getMessage() method:
  • 14. The Call Stack Explained
  • 15. Try-with-resources
  • 15.1 with one resource
  • 15.2 with Multiple resource
  • 15.3 Custom AutoClosable Implementations

Was this helpful?

exception1

Previousexception0Nextexception2

Last updated 5 years ago

Was this helpful?

7. Java Exception propagation

An exception is first thrown from the top of the stack and if it is not caught, it drops down the call stack to the previous method, If not caught there, the exception again drops down to the previous method, and so on until they are caught or until they are caught or until they reach the very bottom of the call stack. This is called exception propagation.

class TestExceptionPropagation1{  
  void m(){  
    int data=50/0;  
  }  
  void n(){  
    m();  
  }  
  void p(){  
   try{  
    n();  
   }catch(Exception e){System.out.println("exception handled");}  
  }  
  public static void main(String args[]){  
   TestExceptionPropagation1 obj=new TestExceptionPropagation1();  
   obj.p();  
   System.out.println("normal flow...");  
  }  
}  
//output
//exception handled
// normal flow

In the above example exception occurs in m() method where it is not handled,so it is propagated to previous n() method where it is not handled, again it is propagated to p() method where exception is handled.

Exception can be handled in any method in call stack either in main() method,p() method,n() method or m() method.

RULE: By default, checked exceptions are not forwarded in calling chain(propagated).

8. Java Throws keyword

The Java throws keyword is used to declare an exception.

If a method needs to be able to throw an exception, it has to declare the exception(s) thrown in the method signature, and then include a throw- statement in the method.

8.1 Syntax of java throws

return_type method_name()throws exception_class_name{
    //method code
    ...throw ....Exception(...);
}

8.2 Which exception should be declared

Checked exception only.

reasons:

  • unchecked Exception: under your control so correct your code

  • error: beyond your control e.g. you are unable to do anything if there occurs VirtualMachineError or StackOverflowError.

8.3 Advantage of Java throws keyword

Now Checked Exception can be propagated(forwarded in call stack).

It provides information to the caller of the method about the exception.

8.4 Java throws example

import java.io.*;

class Testthrows1{  
  void m()throws IOException{  
    throw new IOException("device error");//checked exception  
  }  
  void n()throws IOException{  
    m();  
  }  
  void p(){  
   try{  
    n();  
   }catch(Exception e){System.out.println("exception handled");}  
  }  
  public static void main(String args[]){  
   Testthrows1 obj=new Testthrows1();  
   obj.p();  
   System.out.println("normal flow...");  
  }  
}

output:

exception handled

normal flow...

RULE:

If you are calling a method that declares an exception, you must either caught or declare the exception.

there are two cases:

  • Case1: You caught the exception i.e. handle the exception using try/catch.

  • Case2: You declare the exception i.e. specifying throws with the method.

9. Throw VS Throws

No.

throw

throws

1)

Java throw keyword is used to explicitly throw an exception.

Java throws keyword is used to declare an exception.

2)

Checked exception cannot be propagated using throw only.

Checked exception can be propagated with throws.

3)

Throw is followed by an instance.

Throws is followed by class.

4)

Throw is used within the method.

Throws is used with the method signature.

5)

You can not throw multiple exceptions.

You can declare multiple exceptions e.g. public void method()throws IOException, SQLException.

10. Difference between final, finally and finalize

No.

final

finally

finalize

1)

Final is used to apply restrictions on class, method and variable. Final class can't be inherited, final method can't be overridden and final variable value can't be changed.

Finally is used to place important code, it will be executed whether exception is handled or not.

Finalize is used to perform clean up processing just before object is garbage collected.

2)

Final is a keyword.

Finally is a block.

Finalize is a method.

11. ExceptionHandling with MethodOverriding in Java

RULES:

  • If the superclass method does not declare an exception, subclass overridden method cannot declare the checked exception but it can declare unchecked exception.

  • If the superclass method declares an exception, subclass overridden method can declare same, subclass exception or no exception but cannot declare parent exception.

Checked exception:

  • IOException

  • SQLException

  • ClassNotFoundException

Unchecked exception:

  • ArithmeticException

  • NullPointerException

  • NumberFormatException

  • IndexOutOfBoundsException : 1. ArrayIndexOutOfBoundsException 2. StringIndexOutOfBoundsException

12. Java Custom Exception

Java custom exceptions are used to customize the exception according to user need. By the help of custom exception , you can have your own exception and message.

e.g.

class InvalidAgeException extends Exception{
    InvalidAgeException(String s){
        super(s);

    }
}
class TestCustomException{
    static void validate(int age) throws InvalidAgeException{
        if(age<18) throw new InvalidAgeException("not valid");
        else System.out.println("Hello world");
    }

    public static void main(String[] args) {
        try{
            validate(13);
        }catch(Exception e){
            System.out.println("exception occured: "+e);
        }
        System.out.println("rest code...");
        try {
            System.out.println(50/0);
        } catch (Exception e) {
            //TODO: handle exception
            System.out.println(e);
        }
    }
}

output:

exception occured: InvalidAgeException: not valid
rest code...
java.lang.ArithmeticException: / by zero

13. 3 Different ways to print Exception messages in Java

All of these three ways are present in Throwable class. Since Throwable is the base class for all exceptions and errors, so we can use these three methods on any object.

13.1 java.lang.Throwable. printStackTrace() method:

By using this method, we will get name(e.g. java.lang.ArithmeticException) and description(e.g. / by zero) of an exception separated by colon, and stack trace (where in the code, that exception has occurred) in the next line.

e.g.

public class test{
    public static void main(String[] args){
        try {
            int a = 20/0;
        } catch (Exception e) {
            //TODO: handle exception
            e.printStackTrace();
            System.out.println(e);
        }
    }
}

13.2 toString() method:

By using this method, we will only get name and description of an exception. Note that this method is overridden in Throwable class.

e.g.

public class test{
    public static void main(String[] args){
        try {
            int a = 20/0;
        } catch (Exception e) {

            System.out.println(e.toString());
        }
    }
}

13.3 java.lang.Throwable.getMessage() method:

By using this method, we will only get description of an exception.

e.g.

public class test{
    public static void main(String[] args){
        try {
            int a = 20/0;
        } catch (Exception e) {

            System.out.println(e.getMessage());
        }
    }
}

14. The Call Stack Explained

This text refers to the concept the "call stack" in several places. By the call stack is meant the sequence of method calls from the current method and back to the main Method of the program. If a method A calls B, and B calls C then the call stack looks like this:

A
B
C

When method C returns the call stack only contains A and B. If B then calls the method D, then the call stack looks like this:

A
B
D

15. Try-with-resources

15.1 with one resource

In java 7 we can write the code from the example above using the try-with-resource construct like this:

private static void printFileJava7() throws IOException{
    try(FileInputStream input = new FileInputStream("file.txt")){
        int data = input.read();
        while(data!=-1){
            System.out.println((char) data);
            data = input.read();
        }
    }
}

When the try block finishes the FileInputStream will be closed automatically. This is possible because FileInputStream implements the Java interface java.lang.AutoCloseable. All classes implementing this interface can be used inside the try-with-resources construct.

If an exception is thrown both from inside thetry-with-resourcesblock, and when theFileInputStreamis closed (whenclose()is called), the exception thrown inside thetryblock is thrown to the outside world. The exception thrown when theFileInputStreamwas closed is suppressed. This is opposite of what happens in the example first in this text, using the old style exception handling (closing the resources in thefinallyblock).

15.2 with Multiple resource

private static void printFileJava7() throws IOException {

    try(  FileInputStream     input         = new FileInputStream("file.txt");
          BufferedInputStream bufferedInput = new BufferedInputStream(input)
    ) {

        int data = bufferedInput.read();
        while(data != -1){
            System.out.print((char) data);
    data = bufferedInput.read();
        }
    }
}

This example creates two resources inside the parentheses after thetrykeyword. AnFileInputStreamand aBufferedInputStream. Both of these resources will be closed automatically when execution leaves thetryblock.

The resources will be closed in reverse order of the order in which they are created / listed inside the parentheses. First theBufferedInputStreamwill be closed, then theFileInputStream.

15.3 Custom AutoClosable Implementations

The try-with-resources construct does not just work with Java's built-in classes. You can also implement the java.lang.AutoClosable interface in your own classes, and use them with the try-with-resources construct.

The AutoClosable interface only has a single method called close().

public class MyAutoClosable implements AutoCloseable{
    public void doIt(){
        System.out.println("MyAutoclosable doing it.");
    }

    @Override
    public void close() throws Exception{
        System.out.println("MyAutoClosable closed!");
    }

    private static void myAutoClosable() throws Exception{
        try(MyAutoClosable myAutoClosable = new MyAutoClosable()){
            myAutoClosable.doIt();
            System.out.println("in the myAutoClosable!");
        }
        catch(Exception e){
            System.out.println("in catch");
        }
    }

    public static void main(String[] args) {
        System.out.println("main begin!");
        try {
            myAutoClosable();
        } catch (Exception e) {
            //TODO: handle exception
            System.out.println("main catch!");
        }

    }
}

output:

main begin!
MyAutoclosable doing it.
in the myAutoClosable!
MyAutoClosable closed!

https://www.javatpoint.com/exception-handling-in-java
https://www.javatpoint.com/exception-handling-with-method-overriding
http://tutorials.jenkov.com/java-exception-handling/basic-try-catch-finally.html