What is the control flow, when Exception occurs

Below is an example showing different flow of control, when different Exception occurs, during program execution.
However, exceptions should not be used only to control the flow, rather appropriate control flow statements can be used.


public class ExceptionControlFlow {
	public static void main(String[] args){
	try{
	System.out.println("stmt 1");
	Object obj = null; 
	System.out.println("stmt 2");
	obj.getClass(); //NullPointerException
	System.out.println("stmt 3");
	}
	catch(NullPointerException et)
	{
	System.out.println("stmt 4");
	System.out.println("Exception occurred:"+et.getMessage());
	}
	catch(Exception ep)
	{
	System.out.println("stmt 5");
	}
	}

}

can exceptions be nested

Exceptions can be nested, that means a try block can exist within another try block. Also note that a try block can exist in a catch block.

Below is an example showing nesting of Java Exceptions.


public class SimpleException {

	public static void main(String[] args) {
	try{
	System.out.println("in try");
	
	int arr[] = new int[20];
	
	arr[40] = 23;
	System.out.println("in try 2");
	
	try{
	if(true)
	{
	throw new Exception("Sample Exception");
	}
	}
	catch(Exception en)
	{
	System.out.println("Nested try catch:"+en.getMessage());
	}
	System.out.println("end of outside try");
	}
	catch(ArithmeticException e)
	{
	System.out.println("AE occurred:"+e.getMessage());
	}
	catch(ArrayIndexOutOfBoundsException ae)
	{
	System.out.println("ABE occurred:"+ae.getMessage());
	}
	catch(Exception en)
	{
	en.printStackTrace();
	System.out.println("Exception occurred:"+en.getMessage());
	}
	}

}

how to use throws in handling Exceptions

As briefed in difference between Checked and Unchecked Exception, unchecked exceptions may or may not be handled. But, be aware that all Checked Exceptions either need to be handled using try and catch blocks or need to be further thrown using throws keyword. However it is responsibility of invokers of the method(which throws Exception) to handle it with try catch blocks, or further throw using throws keyword.

throws keyword need to be used along with method declaration, it just indicates that the method may throw an Exception, and invokers of the method need to either handle it or further throws it.

Also note that multiple Exceptions separated with comma, can be used with throws keyword. For eg

public void show() throws NullPointerException, Exception
{
//..statements
}

This feature, helps third party framework to throw an Exception, and let application developers to handle it appropriately.

Below is an example of throws keyword.


class TDemo1{
	public void met1() throws Exception
	{
	if(true)
	{
		throw new Exception("Some Exception");
	}
	}
}

class TDemo2{
	public void met2() throws Exception,NullPointerException
	{

	TDemo1 td = new TDemo1();
		
	td.met1();
	}
}

public class ThrowsDemo {
	public static void main(String args[]) throws Exception
	{
	try{
	TDemo2 td2 = new TDemo2();
	td2.met2();
		
	}catch(Exception e)
	{
		
	e.printStackTrace();
	//printsline number, class name, file name where the exception has occurred
	//and the methods thru which exception has been propogated, until caught
	throw e;//further rethrowing the exception
	}
	finally{
	System.out.println("dsdsfds");
	}
		
	}
}

You may also like to read:
Create user defined Exception
How to create Unchecked Exception
List of exceptions in java.lang package

How to redirect System.out output to a file, instead of Console

You can read about standard input ans standard output stream details here. As known System.out represents Standard output stream, and anything written to standard output stream, gets displayed on console screen. How ever it is possible to redirect output of System.out to any OutputStream, like FileOutputStream, or to Network. Below is an example, on how to redirect the content written to System.out to a file name abcd.txt.

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;

public class SystemIORedirectDemo {
public static void main(String[] args) {
	try{
	FileOutputStream fos = new FileOutputStream("abcd.txt");
	PrintStream ps = new PrintStream(fos);
	System.setOut(ps);
	
	System.out.println("Hello, How are you");
	System.out.println("Note that this content is saved to abcd.txt file");
	}
	catch(IOException ioe)
	{
		System.out.println("IOException occurred:"+ioe.getMessage());
	}
}
}

By default, System.in reads each character from Keyboard. Below is an example on how to redirect System.in. Similarly it is also possible to redirect System.err

import java.io.FileInputStream;
import java.io.IOException;

public class SystemIORedirect1Demo {
public static void main(String[] args) throws IOException{
	FileInputStream fis = new FileInputStream("abcd.txt");
	
	System.setIn(fis);
	
	int i = 0;
	while(i != -1)
	{
	i = System.in.read();//reads each character from the file abcd.txt
	System.out.print((char)i);//prints the character read, above
	}
}
}

You may also like to read:

java standard input and output

In Thread, purpose of join() and isAlive() methods

As known below are the methods available in Thread class
setName()
getName()
setPriority()
getpriority()
sleep()
start()
join()
isAlive()

When to use join() method. Before we try to understand join(), lets see what is Daemon thread. A Daemon thread is a thread, which keeps on running in the background, even though its parent , has already completed execution, and no more exit. Daemon threads, can be avoided using join() method. Whenever join() is invoked, with a thread object(say t1). Execution of main threads waits, until thread t1 completes execution.

Also isAlive() method is provided, just to check if an invoking thread, is still alive, or has completed execution.
isAlive() returns true if invoking thread is still alive, else returns false.

Below is an example, showing, how main thread is kept alive until all child threads have completed execution.


class NewThread1 implements Runnable{
	String name; //name of Thread
	Thread t;
	
	NewThread1(String threadname){
		name=threadname;
		t = new Thread(this,name);
		System.out.println("New thread:"+t);
		t.start();
	}
	
	public void run(){
		try
		{
		for(int i=5;i>0;i--)
		{
		System.out.println(name+":"+i);
		Thread.sleep(1000);
		}
		}
		catch(InterruptedException ie){
		System.out.println(name+" Interrupted");
		}
		
		System.out.println(name+" Exiting");
	}
	
	
}


public class JoinCheck {
	public static void main(String args[])
	{
		NewThread1 nt1=new NewThread1("One");
		NewThread1 nt2;
		NewThread1 nt3;
		NewThread1 nt4;
		//start the threads
		//nt1=new NewThread1("One");
		nt2=new NewThread1("Two");
		nt3=new NewThread1("Three");
		nt4=new NewThread1("Four");
		
		threads_status(nt1,nt2,nt3,nt4);
	try
	{
		nt1.t.join();
		nt2.t.join();
		nt3.t.join();
		nt4.t.join();
		
		
	System.out.println("completed all four threads");
	}catch(Exception ien)
	{
	System.out.println("main thread Interrupted");
	}
	
	threads_status(nt1,nt2,nt3,nt4);
	System.out.println("main thread Exiting");
	}

	private static void threads_status(NewThread1 nta,NewThread1 ntb,NewThread1 ntc,NewThread1 ntd)
	{
	System.out.println("Thread One Alive?"+nta.t.isAlive());
	System.out.println("Thread Two Alive?"+ntb.t.isAlive());
	System.out.println("Thread Three Alive?"+ntc.t.isAlive());
	System.out.println("Thread Four Alive?"+ntd.t.isAlive());
	}
	
}

Output:
New thread:Thread[One,5,main]
New thread:Thread[Two,5,main]
New thread:Thread[Three,5,main]
Two:5
New thread:Thread[Four,5,main]
Thread One Alive?true
Thread Two Alive?true
Thread Three Alive?true
Thread Four Alive?true
Four:5
One:5
Three:5
Two:4
One:4
Four:4
Three:4
Two:3
Four:3
One:3
Three:3
Two:2
Four:2
One:2
Three:2
Two:1
Four:1
One:1
Three:1
Two Exiting
One Exiting
Four Exiting
Three Exiting
completed all four threads
Thread One Alive?false
Thread Two Alive?false
Thread Three Alive?false
Thread Four Alive?false
main thread Exiting

You may also like to read:
What is Thread pool
How to avoid deadlocks in threads
What is a thread
Start a child thread, from another child thread

Why rethrow an Exception in Java?

What is rethrowing an Exception

When an Exception is thrown from your code,
1. You can handle handle the Exception completely, by using try and catch blocks you handle the Exception, and further throw the Exception object. OR
2. Use throws with method declaration, to indicate that invokers of the method need to handle the Exception, or further throws it.

Another option we have here is a combination of above both. That is, the Exception is handled, with try, catch blocks, and further throw the Exception.

Below is an example, of the same.

class TDemo22{
	public void met2() throws Exception
	{
	try
	{
	String str="2abcd3";

	int i = Integer.parseInt(str);
	}
	catch(Exception ep)
	{
	System.out.println("Exception catching");
	throw ep;
	}
	}
}

public class NumberFormatDemo {
	public static void main(String args[])
	{
	try{
	TDemo22 td2 = new TDemo22();
	td2.met2();

	}catch(Exception e)
	{
	e.printStackTrace();
	}
	}
}

There are two different ways, an Exception can be re thrown.
1. catch an Exception, and further throw same Exception object(as shown in above example)
2. catch an Exception, and further create a new Exception object, and throw it(as shown in below example)

class MyException extends Exception{
}

class TDemo22{
	public void met2() throws Exception
	{
	try
	{
	String str="2abcd3";

	int i = Integer.parseInt(str);
	}
	catch(Exception ep)
	{
	System.out.println("Exception catching");
	throw new MyException(); //re throwing a new Exception object
	}
	}
}

public class NumberFormatDemo {
	public static void main(String args[])
	{
	try{
	TDemo22 td2 = new TDemo22();
	td2.met2();

	}catch(Exception e)
	{
	e.printStackTrace();
	}
	}
}

When rethrowing an Exception may be required?
1. When you want to partially handle Exception situation, and further let invokers of your method, to handle the Exception.
2. When you want to hide class name of your internal exception, and rethrow another Exception.

You may also like to read:
How to print stack trace to a log file
List of inbuilt exception in Java
What is RuntimeException
How to create your own Exception?

Create Thread using Anonymous inner class

As briefed, a Thread is light weight process.

Below is an example, on how to create and start Thread, using Anonymous inner class.

Create Anonymous inner class, which extends from java.lang.Thread and override public void run() method.

public class ThreadAnonymousInnerClass {
	public static void main(String args[])
	{
		Thread t1=new Thread(){
		public void run(){
		for(int i=0;i<=10;i++){
		try{
		System.out.println("Thread t1: "+i);
		Thread.sleep(100);  //100 milliseconds
		}catch(InterruptedException e){
		System.out.println("Exception:"+e.getMessage());
		}
		}
		}
		};

		t1.start();

		for(int i=0;i<=10;i++){
		try{
		System.out.println("Main Thread: "+i);
		Thread.sleep(100);  //100 milliseconds
		}catch(InterruptedException e){
		System.out.println("Exception:"+e.getMessage());
		}
		}
	}
}

Create Anonymous class by implementing Runnable interface

How to create Thread, using anonymous class for Runnable. In below example, we are creating object of an anonymous class which implements Runnable interface.

public class ThreadAnonymousRunnable {
	public static void main(String args[])
	{
		new Thread( new Runnable() {
		    public void run() {

              for(int i=0;i<10;i++)
    	      {
    		System.out.println("child_thread: "+i);
    		try
    		{
    			Thread.sleep(100);
    		}catch(InterruptedException ie){
    			System.out.println(ie.getMessage());
    		}
    	     }
		    }
		}).start();

		for(int i=0;i<10;i++)
    	        {
    		System.out.println("main_thread: "+i);
    		try
    		{
    			Thread.sleep(100);
    		}catch(InterruptedException ie){
    			System.out.println(ie.getMessage());
    		}
    	        }
	}
}

Further reducing size of code

public class ThreadAnonymousRunnable {

	private static void thread_body(String thread_name)
	{
		for(int i=0;i<10;i++)
    	{
    		System.out.println(thread_name+": "+i);
    		try
    		{
    			Thread.sleep(100);
    		}catch(InterruptedException ie){
    			System.out.println(ie.getMessage());
    		}
    	}
	}

	public static void main(String args[])
	{
		new Thread( new Runnable() {
		    public void run() {

		    	thread_body("child_thread");
		    }
		}).start();

		thread_body("main_thread");
	}
}

You may also like to read:
purpose of synchronized keyword
how to use synchronized with a class
how to use synchronized with a method
what are concurrent collections

List of Built in Exceptions in Java

Built in Exception are in java.lang package.
Before we see list of builtin Checked and UnChecked Exceptions, please read difference between checked and unchecked Exceptions.

Below is list of Checked Exceptions
Checked Exceptions are derived from Exception class

Exception name Reason & sample code
1. ClassNotFoundException Class is not found.
Class.forName(“p1.Abcd”);
2. CloneNotSupportedException Tried cloning an object that does not implement Cloneable interface.
obj.clone();
3. IllegalAccessException Do not have Access to a class.
obj.newInstance();
4. InstantiationException Cannot create an object of an abstract class or interface.
obj.newInstance();
5. InterruptedException One thread has been interrupted by another thread.
Thread.sleep();
6. NoSuchFieldException Field used does not exist.
cls.getField(“string3”);
7. NoSuchMethodException Method requested does not exist.
c.getMethod(“display”, null);

Below is list of UnChecked Exceptions
Unchecked Exception are classes derived from java.lang.Exception

Exception name Reason & Sample code
1. ArithmeticException Arithmetic error, such as divide-by-zero.
int i=32/0;
2. ArrayIndexOutOfBoundsException Array index is out-of-bounds.
arr[20]=56;
3. ArrayStoreException Assignment to an array element of an incompatible type.
arr=brr;
4. ClassCastException Invalid casting.
A obj = (A)(new B());
5. IllegalArgumentException Illegal argument used to invoke a method.
6. IllegalMonitorStateException Illegal monitor operation, such as waiting on an unlocked thread.
7. IllegalStateException Environment or application is in incorrect state.
8. IllegalThreadStateException Requested operation not compatible with current thread state.
9. IndexOutOfBoundsException index is out of range.
10. NegativeArraySizeException Array created with a negative size.
int arr[]=new int[-5];
11. NullPointerException Attempted to refer null.
12. NumberFormatException A String of invalid format attempted to convert.
Integer.parseInt(“3sd”);
13. SecurityException Attempt to violate security.
14. StringIndexOutOfBounds Attempt to index outside the bounds of a string.
str.charAt();
15. UnsupportedOperationException An unsupported operation was encountered.

You may also like to read:
How to create Custom exception in Java

Can we have single catch to handle multiple Exceptions

Yes, it is possible to have single catch to handle multiple Exceptions. But this syntax is supported only after Java 7 version.
Below is an example of the same.

public class MultipleExceptions
{
public static void main(String args[])
{
try {
  int j;

  int arr[] = new int[10];
  j = 42/0;
  arr[20] = 56;
} catch( ArithmeticException | IndexArrayOutOfBoundsException ex ) {
  System.out.println(ex.getMessage());
  ex.printStackTrace();
}
}
}

You may also like to read:

Starting a thread from another thread instead of main thread

Below is an example showing how to start another Thread, from non main thread.

#1.In main method, a thread t1 is started.
#2.In run() method of thread t1, another thread t2 is started.

class thread1 implements Runnable{
public void run(){
System.out.println("inside thread 1 now printing numbers");
for(int i=0;i<10;i++){
System.out.println(i);
}

Thread t2=new Thread(new thread2());

t2.start();


}
}
class thread2 implements Runnable{

public void run(){
System.out.println("inside thread2...");
System.out.println("program which we run has shown that we can invoke or start another thread"
+" out of the main thread also");
}
}
public class threaddemo {
public static void main (String[] args) {
Thread t1= new Thread(new thread1());
System.out.println("starting thread 1");

t1.start();


}

}


Output-

starting thread 1
inside thread 1 now printing numbers
0
1
2
3
4
5
6
7
8
9
inside thread2…
program which we run has shown that we can invoke or start another thread out of the main thread also

You may like to read:
Multi threading example
purpose of PipedInputStream and PipedOutputStream
What is block level synchronization?
What is class level synchronization?