Core java - Advance Topics
  • Welcome
  • Schedule
  • 1) Exception Handling
    • 1) Introduction to Exception Handling
    • 2) Categories of Exceptions
    • 3) Creating a method that throws an exception
    • 4) Creating Custom Exception Classes
    • 5)What happens when an exception is thrown?
      • 5.1) Creating try-catch-finally blocks
      • 5.2) Using a method that throws a checked exception
      • 5.3) Using a method that throws a runtime exception
      • 5.4) Using a method that throws an error
      • 5.5) Will a finally block execute even if the catch block defines a return statement?
      • 5.6) What happens if both a catch and a finally block define return statement?
      • 5.7) What happens if a finally block modifies the value returned from a catch block?
      • 5.8) Can a try block be followed only by a finally block?
      • 5.9) Does the order of the exceptions caught in the catch blocks matter?
      • 5.10) Can I rethrow an exception or the error I catch?
      • 5.11) Can I declare my methods to throw a checked exception instead of handling it?
      • 5.12) I can create nested loops, so can I create nested try-catch blocks too?
      • 5.13) Should I handle errors?
    • 6) Best Practices
    • 7) Cheat Sheet
    • 8) Problems
  • 2) Wrapper Classes and Enums
    • 2.1) Creating objects of the wrapper classes
    • Enums
  • 3) Inner Classes
    • 3.1) Static nested class (also called static inner class)
    • 3.2) Inner class (also called member class)
    • 3.3) Anonymous inner class
    • 3.4) Method local inner classes
    • CheatSheet
  • 4) Generics
    • Multiple Type parameters in Generic classes
    • Inheritance using Generics
    • Generic interfaces
    • Generic Methods
    • Bounded type parameters
    • Applications
  • 5) Equals and Hashcode
    • Problems
  • CompareTo method overview
  • Basic DS
    • 1) Simple Array List
    • 2) Simple HashMap
  • 5) Collections Framework - Part 1
    • Introducing the collections framework
    • Working with the Collection interface
      • The core Collection interface
      • Methods of the Collection interface
    • Creating and using List, Set, and Deque implementations
      • List interface and its implementations
      • Iterators
      • Sorting List using custom sorting technique
      • Comparable Interface
      • Custom Sorting using comparator
      • ArrayList - Examples and practice problems
    • Stack
    • Linked List
    • LinkedList Operations
  • 6) Collections Framework - Part 2
    • Sets
      • Set Types
      • Array to Set (vice versa)
    • Maps
    • TreeMap
    • Autoboxing And Unboxing
  • Collections Framework - Part 3
    • Basics : DS , Number System
    • Internal Working
      • HashMap
      • HashSet
  • 7) Reflection API
  • 8) Annotations
  • 9) Reading Input From Various Sources
    • File Handling
    • Reading From Xml
    • Reading From JSON
  • 10) Multi-threading (Concurrency)
    • Protect shared data
    • Thread-safe access to shared data
  • 11) Design Patterns
    • Singleton
    • DI
  • 12) Internal Working of JVM
  • 13) Garbage Collection
  • 14) More on Strings (Buffer and Builder)
  • 15) Cloning and Immutable Class
    • 16) Serialization And Deserialization
    • Untitled
  • JAVA 8
    • Interface Changes
    • Lambda
    • Method Ref
    • Optional
    • Streams
    • Predicates
  • Practice Tests
    • Test - Collections
    • OOPS
    • S-OOPS
Powered by GitBook
On this page
  • Exception Handling
  • Exception
  • Types of exceptions
  • Why use Exception Handling
  • Example without Exception Handling:
  • Example of Exception Handling:
  • try Block:
  • catch block:
  • finally block:
  • throw keyword :
  • throws keyword:

Was this helpful?

  1. 1) Exception Handling

1) Introduction to Exception Handling

Exception Handling

The process of converting system error messages into user friendly error message is known as Exception handling. This is one of the powerful features of Java to handle run time error and maintain normal flow of java application.

Exception

An Exception is an event, which occurs during the execution of a program that disrupts the normal flow of the program's Instructions.

Types of exceptions

There are two types of exceptions in Java: 1)Checked exceptions 2)Unchecked exceptions

Checked exceptions

All exceptions other than Runtime Exceptions are known as Checked exceptions as the compiler checks them during compilation to see whether the programmer has handled them or not. If these exceptions are not handled/declared in the program, you will get compilation error. For example, SQLException, IOException, ClassNotFoundException etc.

Unchecked Exceptions

Runtime Exceptions are also known as Unchecked Exceptions. These exceptions are not checked at compile-time so compiler does not check whether the programmer has handled them or not but it’s the responsibility of the programmer to handle these exceptions and provide a safe exit. For example, ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.

Why use Exception Handling

Handling the exception is nothing but converting system error generated message into user friendly error message in others word whenever an exception occurs in the java application, JVM will create an object of appropriate exception of sub class and generates system error message, these system generated messages are not understandable by user so need to convert it into user-friendly error message. You can convert system error message into user-friendly error message by using exception handling feature of java.

There are five keywords for Handling the Exception

· Try

· Catch

· Finally

· Throw

· throws

Syntax for handling the exception

Example without Exception Handling:

public class ExceptionHandling {
	public static void main(String[] args) {
		int a=10, b=0;
		b=a/0;
		System.out.println("===Ececuted this Line===");                              
	}
}

As you observe, Abnormally terminate program and give a message like above, this error message is not understandable by user so we convert this error message into user friendly error message, like "denominator not be zero".

Example of Exception Handling:

public class ExceptionHandling {

	public static void main(String[] args) {
		int a=10, b=0;
		try
		{
		b=a/0;
		}
		catch (Exception e)
		{
		System.out.println("Denominator not be zero");
		}            
                          
	}
}

try Block:

Inside try block we write the block of statements which causes executions at run time in other words try block always contains problematic statements.

Important points about try block

· If any exception occurs in try block then CPU controls comes out to the try block and executes appropriate catch block.

· After executing appropriate catch block, even though we use run time statement, CPU control never goes to try block to execute the rest of the statements.

· Each and every try block must be immediately followed by catch block that is no intermediate statements are allowed between try and catch block.

· Each and every try block must contain at least one catch block. But it is highly recommended to write multiple catch blocks for generating multiple user friendly error messages. One try block can contains another try block that is nested or inner try block can be possible.

catch block:

Inside catch block we write the block of statements which will generates user friendly error messages.

Catch block important points

Catch block will execute exception occurs in try block.

You can write multiple catch blocks for generating multiple user friendly error messages to make your application strong.

Multiple catch block:

You can write multiple catch blocks for generating multiple user friendly error messages to make your application strong. You can see below example.

import java.util.*;

public class ExceptionDemo {
	public static void main(String[] args) {
		int a, b, ans = 0;
		Scanner s = new Scanner(System.in);
		System.out.println("Enter any two numbers: ");
		try {
			a = s.nextInt();

			b = s.nextInt();

			ans = a / b;

			System.out.println("Result: " + ans);
		} catch (ArithmeticException ae) {
			System.out.println("Denominator not be zero");
		}

		catch (Exception e) {
			System.out.println("Enter valid number");
		}
	}
}

finally block:

It is a block that is used to execute important code such as closing connection, stream etc.

Java finally block is always executed whether exception is handled or not.

Java finally block must be followed by try or catch block.

Why use java finally

Finally block in java can be used to put "cleanup" code such as closing a file, closing connection etc.

Usage of Java finally

class TestFinallyBlock {
	public static void main(String args[]) {
		try {
			int data = 25 / 5;
			System.out.println(data);
		} catch (NullPointerException e) {
			System.out.println(e);
		} finally {
			System.out.println("finally block");
		}
		System.out.println("rest of the code");
	}
}

Way to skip finally block

public class Main {
    public static void main(String[] args) {
        try {
            System.out.println("Hi");
            System.exit(0);
        }
        finally {
            System.out.println("Bye!");
        }
    }
}

In the above code by calling system.exit in try block terminates the JVM due to wich finally block will not be executed.

throw keyword :

/* In this program we are checking the Student age
 * if the student age<12 and weight <40 then our program 
 * should return that the student is not eligible for registration.
 */
public class ThrowExample {
	static void checkEligibilty(int stuage, int stuweight) {
		if (stuage < 12 && stuweight < 40) {
			throw new ArithmeticException("Student is not eligible for registration");
		} else {
			System.out.println("Student Entry is Valid!!");
		}
	}

	public static void main(String args[]) {
		System.out.println("Welcome to the Registration process!!");
		try {
			checkEligibilty(10, 39);
		} catch (Exception e) {
			System.out.println(e);
		}
		System.out.println("Have a nice day..");
	}
}

throws keyword:

As we know that there are two types of exception checked and unchecked. Checked exception (compile time) force you to handle them, if you don’t handle them then the program will not compile. On the other hand unchecked exception (Runtime) doesn’t get checked during compilation. Throws keyword is used for handling checked exceptions. By using throws we can declare multiple exceptions in one go.

What is the need of having throws keyword when you can handle exception using try-catch?

Lets say we have a method myMethod() that has statements that can throw either ArithmeticException or NullPointerException, in this case you can use try-catch as shown below:

public void myMethod()
{
  try {
    // Statements that might throw an exception 
  }
  catch (ArithmeticException e) {
    // Exception handling statements
  }
  catch (NullPointerException e) {
    // Exception handling statements
  }
}

But suppose you have several such methods that can cause exceptions, in that case it would be tedious to write these try-catch for each method. The code will become unnecessary long and will be less-readable.

One way to overcome this problem is by using throws like this: declare the exceptions in the method signature using throws and handle the exceptions where you are calling this method by using try-catch. Another advantage of using this approach is that you will be forced to handle the exception when you call this method, all the exceptions that are declared using throws, must be handled where you are calling this method else you will get compilation error.

public void myMethod() throws ArithmeticException, NullPointerException
{
  // Statements that might throw an exception 
}

public static void main(String args[]) { 
  try {
    myMethod();
  }
  catch (ArithmeticException e) {
    // Exception handling statements
  }
  catch (NullPointerException e) {
    // Exception handling statements
  }
}

Example of throws Keyword

In this example the method myMethod() is throwing two checked exceptions so we have declared these exceptions in the method signature using throws Keyword. If we do not declare these exceptions then the program will throw a compilation error.

import java.io.*;

class ThrowExample {
	void myMethod(int num) throws IOException, ClassNotFoundException {
		if (num == 1)
			throw new IOException("IOException Occurred");
		else
			throw new ClassNotFoundException("ClassNotFoundException");
	}
}

public class Example1 {
	public static void main(String args[]) {
		try {
			ThrowExample obj = new ThrowExample();
			obj.myMethod(1);
		} catch (Exception ex) {
			System.out.println(ex);
		}
	}
}

Previous1) Exception HandlingNext2) Categories of Exceptions

Last updated 6 years ago

Was this helpful?