Day 12- Exceptions

What is an Exception ?

An unwanted , unexpected event that disturbs the normal flow of the program is called an Exception.

  • Its highly recommendable to handle an exception.
  • The main purpose of exception handling is graceful termination of the program.
  • Exception handling doesn’t mean repairing an exception, it means defining an alternative way to continue rest of the program normally.
  • For example, if our program needs to access a file which is located in London and it isn’t available at the moment then it shouldnt be terminated abnormally, we have to provide some alternative to continue rest of program (like providing a local file). This way of defining an alternative is known as “Exception handling”.

Default Exception handling in Java

Inside any method if any exception occurs, then the method in which Exception has occurred is responsible for the preparation of exception object by including the following information.

  1. Name of the exception,
  2. Description ,
  3. Stack Trace [location of exception]

After creation of exception object, the method handovers the exception object to JVM. JVM now checks whether any exception handling code is present or not. If the method do not contain any exception handling mechanism then it terminates the method abnormally and removes the corresponding method from the stack. JVM identifies the caller method and does the same, this process continues upto main method. Even if the main method do not have any exception handling code then JVM terminates the main() method abnormally and handles the responsibility of “default exception handler” which is a part of JVM. Default exception handler terminates the program abnormally and prints exception information to console in following format

Name of the Exception : Description
Stack Trace. 

Lets take an example to illustrate this :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class  Test
{
	public static void main(String[] args) 
	{
		doStuff();
	}
	 public static void doStuff()
	{
		doMoreStuff();
	}
      public static void doMoreStuff()
	{
		System.out.println(10/0);
	}
}

When you try to execute the code the following can be seen on console

Exception in thread “main” java.lang.ArithmeticException: / by zero
at Test.doMoreStuff(Exceptiondemo.java:13)
at Test.doStuff(Exceptiondemo.java:9)
at Test.main(Exceptiondemo.java:5)

ss2

Exception Hierarchy

Throwable class acts as root for exception hierarchy.

Throwable class contains two child classes

  1. Exception
  2. Error

Exception: In most of the cases these are caused by programs and all are recoverable.

Error: Errors are not caused by program and these are typically due due to lack of system resources. These are non-recoverable.

Checked vs Unchecked Exceptions

Checked Exception : 

The exceptions that are checked by the compiler for smooth execution of program are know as Checked Exception. We should handle checked exceptions in our program to compile.

Unchecked Exception:

These are not checked by the compiler. Hence Unchecked ! They occur in runtime.

Handling Exception by using try-catch-finally

We must handle the exception to prevent abnormal execution of program. The code which may cause exception is known as risky code . We must keep this risky code in try and corresponding handling code in catch. If we need some code which have to be executed no matter exception rises or not, then we should declare it in a finally block.

Some points to note about exceptions 

  • Nesting of try-catch-finally is always possible.
  • For a try block, we have to write either a catch or finally, in other words a try block without corresponding catch or finally is invalid.
  • For try-catch-finally, curly braces are mandatory and order is important.
  • catch, finally without try is invalid.

throw keyword:

By using throw keyword, we can create our own exception object manually. In general, we use throw for customized exception but not for manual exception.

We cannot write any statement after throw , otherwise we would get compile time error saying “Unreachable statement.”

We can use throw keyword only for throwable type otherwise we will get compile time error saying incompatible type.

For example below program is not correct and hence results in error.

1
2
3
4
5
6
7
8
9
10
11
12
13
class Test 
{	
	public static void main(String[] args) 
	{
		throw new Test();
	}
}
/* Test.java:5: error: incompatible types
                throw new Test();
                      ^
  required: Throwable
  found:    Test
1 error*/

This is correct!

1
2
3
4
5
6
7
class Test extends RuntimeException
	{	
	public static void main(String[] args) 
	{
		throw new Test();
	}
}

Exception handling by using throws keyword

We can use throws keyword to delegate the responsibility of handling an exception to the caller(maybe a method or JVM).

We can use throws keyword only for methods and constructors but not for classes.

WE can use throws keyword only for throwable type but not for normal java classes.

1
2
3
4
5
6
7
8
9
10
11
12
13
class Test 
	{	
	public static void main(String[] args) throws cool
	{
		System.out.println("This is cool!");
	}
}
/*Test.java:4: error: cannot find symbol
        public static void main(String[] args) throws cool
                                                      ^
  symbol:   class cool
  location: class Test
1 error*/

Leave a Reply