Understand Java Exception & The effect to Java Program (Single & Multi Thread)

In the tutorial, JavaSampleApproach will introduce Java Exception and its effect to program’s execution in Single & Multi Thread Program.
Related post:
Java 7 – try-with-resources Statement
How to handle Java Exception

I. Java Exception

Java Exception is a problem when executing a code flow and they can stop the execution if not handled carefully. There are 2 kinds of the Exception: CheckedException & UnCheckedException.

1. Java CheckedException

CheckedException is an exception that can be detected by Java compiler. Editors can help developers to detect by highlight them at development time. CheckedException extends java.lang.Exception, some common CheckedException: FileNotFoundException, IOException

Example:

package com.javasampleapproach.exception;

import java.io.File;
import java.io.FileReader;

public class JavaCheckedException {
	public static void main(String[] args){
		String FILE_NAME = "C:\\test\\test.txt";
		FileReader fr = new FileReader(new File(FILE_NAME));
		char[] a = new char[50];
		fr.read(a); // reads the content to the array
		for (char c : a)
			System.out.print(c); // prints the characters one by one
		fr.close();
	}
}

When compile it, there are 3 exceptions:

C:\Program Files\Java\jdk1.8.0_101\bin>javac JavaException.java
JavaException.java:9: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
                FileReader fr = new FileReader(new File(FILE_NAME));
                                ^
JavaException.java:11: error: unreported exception IOException; must be caught or declared to be thrown
                fr.read(a); // reads the content to the array
                       ^
JavaException.java:14: error: unreported exception IOException; must be caught or declared to be thrown
                fr.close();
                        ^
3 errors

C:\Program Files\Java\jdk1.8.0_101\bin>javac JavaException.java
[0x7FFC2B0870E3] ANOMALY: use of REX.w is meaningless (default operand size is 64)
JavaException.java:9: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
                FileReader fr = new FileReader(new File(FILE_NAME));
                                ^
JavaException.java:11: error: unreported exception IOException; must be caught or declared to be thrown
                fr.read(a); // reads the content to the array
                       ^
JavaException.java:14: error: unreported exception IOException; must be caught or declared to be thrown
                fr.close();
                        ^
3 errors

Eclipse Editor for detecting CheckedException:
Java Exception - Checked Exception Eclipse

With CheckedException, developers must handle it by try/catch statement or throws keyword.

Use try/catch:

try{
	String FILE_NAME = "C:\\test\\test.txt";
	FileReader fr = new FileReader(new File(FILE_NAME));
	char[] a = new char[50];
	fr.read(a); // reads the content to the array
	for (char c : a)
		System.out.print(c); // prints the characters one by one
	fr.close();
}catch(FileNotFoundException e){
	// do some thing
	System.out.println(e.getMessage());
}catch(IOException e){
	// do some thing like:
	System.out.println(e.getMessage());
}

or use throws keyword:

public static void main(String[] args) throws IOException{
	String FILE_NAME = "C:\\test\\test.txt";
	FileReader fr = new FileReader(new File(FILE_NAME));
	char[] a = new char[50];
	fr.read(a); // reads the content to the array
	for (char c : a)
		System.out.print(c); // prints the characters one by one
	fr.close();
}
2. Java UncheckedException

UncheckedException is a kind of Exception that occurs at the executing time, so it can be called: RunTime Excepion. UncheckedException does not be detected by compiler because they are related with logic code at runtime.
UncheckedException extends from java.lang.RuntimeException, some common UncheckedException like: NullPointerException, IndexOutOfBoundsException, IllegalArgumentException, ArithmeticException.

Sample java.lang.ArithmeticException: / by zero

public static void main(String[] args) {
	System.out.println("# Code for Test: Unchecked Exception");
	int i = 1;
	int k = 2;
	// do something
	// ...
	// then k = 0;
	k = 0;
	int m = i / k;
	System.out.println(m);
}

Exception when executing:

# Code for Test: Unchecked Exception
Exception in thread "main" java.lang.ArithmeticException: / by zero
	at com.javasampleapproach.exception.JavaUnCheckedException.main(JavaUnCheckedException.java:12)


Runtime Exceptions
are big problems so Developers need to handle it carefully by try/catch statement or throws/throw keyword.

package com.javasampleapproach.exception;

import java.util.logging.Logger;

public class JavaUnCheckedException {
	private static Logger log = Logger.getLogger((JavaUnCheckedException.class.getName()));
	public static void main(String[] args) {
		System.out.println("# Code for Test: Unchecked Exception");
		int i = 1;
		int k = 2;
		int m = 0;
		
		try{
			// do something
			// ...
			// then k = 0;
			k = 0;
			m = i / k;
		}catch(Exception e){
			// do something such as logs it for investigating bugs 
			// then continue process the execution or throw e like it
			log.info(e.getMessage());
			m = -1;
		}
		System.out.println(m);
	}
}
II. Effect of Exceptions to Program Execution

With CheckedException are easy to detected and handled by helping of Java Compiler and Editors. But UncheckedExceptions are very risk, it can stop Program. So Developers need to understand the impact of it in deeply way.

1. Java RunTime Exception in Single Thread Program

Once again with sample java.lang.ArithmeticException: / by zero

public static void main(String[] args) {
	System.out.println("# Code for Test: Unchecked Exception");
	int i = 1;
	int k = 2;
	// do something
	// ...
	// then k = 0;
	k = 0;
	int m = i / k;
	System.out.println(m);
}

The Exception is happened at int m = i / k;, and the program will be terminated right after it. try/catch statement will help program to handle the exception then continue processing remain codes.

System.out.println("# Code for Test: Unchecked Exception");
int i = 1;
int k = 2;
int m = 0;

try{
	// do something
	// ...
	// then k = 0;
	k = 0;
	m = i / k;
	System.out.println(m);
}catch(Exception e){
	// do something such as logs it for investigating bugs 
	// then continue process the execution or throw e like it
	log.info(e.getMessage());
	m = -1;
}
System.out.println(m);

The exception is happened at point: m = i / k;, but The Program uses try/catch to handle it so the program continues processing with code segment: System.out.println(m);.

2. Java RunTime Exception in Multi-Thread Program

Java Exception only affects to a current Thread (the executing flow that causes exception).
Let go with below program has 2 child threads inside, both of them make exception but just only once handling exception:

package com.javasampleapproach.exception;

public class JavaUnCheckedException {
	public static void main(String[] args) {
		System.out.println("# MainThread - Starting:");
		
		Thread threadWithHandleException = new Thread(new ThreadWithHandleException());
		threadWithHandleException.setName("threadWithHandleException");
		Thread threadNotHandleException = new Thread(new ThreadNotHandleException());	
		threadNotHandleException.setName("threadNotHandleException");
		
		threadWithHandleException.start();
		threadNotHandleException.start();
		
		System.out.println("Main Thread - Done!");
	}
	
	
}

class ThreadWithHandleException implements Runnable{
    @Override
    public void run() {
    	System.out.println("## ThreadWithHandleException starting:");
    	int i = 1;
    	int k = 2;
    	int m = 0;

    	try{
    		// do something
    		// ...
    		// then k = 0;
    		k = 0;
    		m = i / k;
    		
    	}catch(Exception e){
    		// do something such as logs it for investigating bugs 
    		// then continue process the execution or throw e like it
    		m = -1;
    		System.out.println("## ThreadWithHandleException Exception Here:");
    	}
    	System.out.println("## m = " + m);
    	System.out.println("## ThreadWithHandleException Done!");
    }
}

class ThreadNotHandleException implements Runnable{
    @Override
    public void run() {
    	System.out.println("### ThreadNotHandleException starting:");
    	int i = 1;
    	int k = 2;
    	// do something
    	// ...
    	// then k = 0;
    	k = 0;
    	int m = i / k;
    	System.out.println("### m = " + m);
    	System.out.println("### ThreadNotHandleException Done!");
    }
}

Result:

# MainThread - Starting:
Main Thread - Done!
## ThreadWithHandleException starting:
## ThreadWithHandleException Exception Here:
### ThreadNotHandleException starting:
## m = -1
## ThreadWithHandleException Done!
Exception in thread "threadNotHandleException" java.lang.ArithmeticException: / by zero
	at com.javasampleapproach.exception.ThreadNotHandleException.run(JavaUnCheckedException.java:57)
	at java.lang.Thread.run(Unknown Source)

The java.lang.ArithmeticException: / by zero terminates threadNotHandleException thread. But it does not impact to the execution of main thread and ThreadWithHandleException thread.

0 0 votes
Article Rating
Subscribe
Notify of
guest
258 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments