Register   Login   About   Study   Enterprise   Share
AI / Internet Technology University (AITU)
Fast Login - available after registration







|

Top Links: >> 80. Technology >> Internet Technology Summit Program >> 1. Java Introduction >> 1.4. Input-Output and Exceptions
Current Topic: 1.4.2. Handling Exceptions
You have a privilege to create a quiz (QnA) related to this subject and obtain creativity score...
Java never crashes the system ? without warnings. Java Exceptions serve as such close calls. Exceptions are the signals issued by JVM to indicate abnormal conditions that can kill a running program. Exception handlers can prevent program termination. A programmer can include the line to throw Exception when detected or provide several lines to try and catch(Exception object).
There are several types of exceptions. For example, any database or input and output operations require handling exceptions. Obviously, many things can go wrong with these operations: network or database can be down, file might not exist, and the list can go on and on. Java compiler will not compile your code if such operations do not have exception handlers. Eclipse will hint you to provide the handlers by underlying with red such lines.
But exceptions can happen in many other cases when your program meets unexpected conditions. The most common problems happen with unexpected data. For example, your calculation includes division to a variable and the variable happen to be 0. Or you try to use an element 5 of the array, but the array only has 3 elements, or maybe the array is null at all. These situations cause a RuntimeException, which has a lot of more specific subclasses.
The RuntimeException and its subclasses do not have to be caught or declared in a throws clause of a methods. There must be a programming logic in place to check all possible conditions and prevent unexpected cases.
All other exceptions must be caught or declared in the throws clause.
You can create your own exception type by extending any of the exception classes. This allows you to create more specific exceptions that may explain a specific condition better.
The Exception class has a parent, the Throwable class.
The hierarchy of classes looks like this:

java.lang.Object - (The java.lang.Object class is a common parent for all Java classes.)
java.lang.Throwable
java.lang.Exception

The Exception class has many children, subclasses. When we throw or try/catch exceptions it is recommended to be as precise as possible in providing the name of the expected exception. For example, in our IO utilities we named the IOException class in the throws clause, not the generic Exception.

When to use try/catch and when throws clause?
To answer this question keep in mind that throws clause is not really a handler. What it does is really passing exception to a higher level which called this method. This higher level method will be forced to try/catch or throw that exception even higher. Eventually your program must catch this exception and handle it ? or die. You catch the exception at the level where you have enough information to meaningfully handle the exception.
For example, we decided to handle the exception in the readTextFile method instead of throwing this exception to the higher level.
In the case of any exception we will return the message that will start with "ERROR:" and will continue with a specific exception message provided by JVM.

The source will look this way:

/**
* The readTextFile() method connects to an existing file and reads from the file
*
* @param name
* @return text or error message
*/
public static String readTextFile(String name) {
String text = ""; // the String object to collect the file
BufferedReader br = null;
try {
FileReader fr = new FileReader(name);
br = new BufferedReader(fr);
// prepare for the loop
String line = ""; // a single line to be filled by the readLine() method
for (; (line = br.readLine()) != null;) {
text += line + System.lineSeparator(); // collecting all lines together
}
} catch (IOException e) {
text = "ERROR: e=" + e.getMessage(); // return error message
} finally { // the finally clause will close the stream even in the case of exception
if (br != null) {
try {
br.close();
} catch (Exception e) {
System.out.println("ERROR: " + e.getMessage());
}
}
}

return text;
}
Was it clear so far?

Note, that we not only used try/catch but we also used the finally keyword. The finally clause will be performed with or without the exception event. Our purpose is to close the reading stream in both cases, so we do not leave OS resources wasted even if something goes wrong with file reading.
We can also handle exceptions in the writeTextFilemethod. Our current writeTextFile method is void. We will change this. The method will return a Boolean value, true or false. The method will return true in the case of successful writing or it will return false if something goes wrong.

/**
* The writeTextFile() method creates a new file and writes a set of lines
* to the file
*
* @param name
* @param lines
* @returns true if success or false in the case of any errors
*/
public static boolean writeTextFile(String name, String[] lines) {
boolean success = true;
PrintWriter pw = null;
try {
FileWriter fw = new FileWriter(name); // create a new file
pw = new PrintWriter(fw); // wrap a convenient stream for writing lines
for (int i = 0; i < lines.length; i++) {
pw.println(lines[i]); // write line by line into the file
}
// flush OS buffers, otherwise OS can wait till the buffers are full
// before writing to a file
} catch (IOException e) {
success = false;
} finally {
pw.flush();
pw.close();
}
return success;
}


In this example we again use the finally block to close the writing stream in any case: with normal or abnormal operation.
Assignments:
1. Read the Exceptions tutorial from Oracle.
2. Open Eclipse and in the project week2 create another package day8. Copy or (better) re-type the IOMaster source to this package. Then modify all methods to handle exceptions as in the examples above. Do not forget to modify the main method and check the results.
3. Open Windows Explorer and navigate to the c:/its-resources folder. Create in this folder another text file with the WordPad, type several lines, and save as day8.txt.
Create another new class TestReadText.
In this class create the main method and in the main method call the utility IOMaster.readTextFile with the argument "c:/its-resources/day8.txt".
The utility will return the text that you typed in this file manually.

Your line in the main method will look like this:
String text = IOMaster.readTextFile("c:/its-resources/day8.txt");

Then add the line to display the text.

When finished, run the main method: Right mouse click on the source ? Run As ? Java Application.
Check the results in the console.
4. In a similar way create and run the following classes: TestWriteText, TestWriteBin, and TestReadBin
Topic Graph | Check Your Progress | Propose QnA | Have a question or comments for open discussion?
<br/>java.lang.Object - (The <b>java.lang.Object</b> class is a common parent for all Java classes.)
<br/>java.lang.Throwable
<br/>java.lang.Exception
<br/>

The Exception class has many children, subclasses. When we throw or try/catch exceptions it is recommended to be as precise as possible in providing the name of the expected exception. For example, in our IO utilities we named the IOException class in the throws clause, not the generic Exception.

When to use try/catch and when throws clause?
To answer this question keep in mind that throws clause is not really a handler. What it does is really passing exception to a higher level which called this method. This higher level method will be forced to try/catch or throw that exception even higher. Eventually your program must catch this exception and handle it ? or die. You catch the exception at the level where you have enough information to meaningfully handle the exception.
For example, we decided to handle the exception in the readTextFile method instead of throwing this exception to the higher level.
In the case of any exception we will return the message that will start with "ERROR:" and will continue with a specific exception message provided by JVM.

The source will look this way:
<br/> 	/**
<br/>	 * The readTextFile() method connects to an existing file and reads from the file
<br/>	 * 
<br/>	 * @param name
<br/>	 * @return text or error message
<br/>	 */
<br/>	public static String readTextFile(String name) {
<br/>		String text = ""; // the String object to collect the file
<br/>		BufferedReader br = null;
<br/>		try {
<br/>			FileReader fr = new FileReader(name);
<br/>			br = new BufferedReader(fr);
<br/>			// prepare for the loop
<br/>			String line = ""; // a single line to be filled by the readLine() method
<br/>			for (; (line = br.readLine()) != null;) {
<br/>				text += line + System.lineSeparator(); // collecting all lines together
<br/>			}
<br/>		} catch (IOException e) {
<br/>			text = "ERROR: e=" + e.getMessage(); // return error message
<br/>		} finally { // the finally clause will close the stream even in the case of exception
<br/>			if (br != null) {
<br/>				try {
<br/>					br.close();
<br/>				} catch (Exception e) {
<br/>					System.out.println("ERROR: " + e.getMessage());
<br/>				}
<br/>			}
<br/>		}
<br/>
<br/>		return text;
<br/>	}
<br/>






Was it clear so far?


Note, that we not only used try/catch but we also used the finally keyword. The finally clause will be performed with or without the exception event. Our purpose is to close the reading stream in both cases, so we do not leave OS resources wasted even if something goes wrong with file reading.
We can also handle exceptions in the writeTextFilemethod. Our current writeTextFile method is void. We will change this. The method will return a Boolean value, true or false. The method will return true in the case of successful writing or it will return false if something goes wrong.
<br/>	/**
<br/>	 * The writeTextFile() method creates a new file and writes a set of lines
<br/>	 * to the file
<br/>	 * 
<br/>	 * @param name
<br/>	 * @param lines
<br/>	 * @returns true if success or false in the case of any errors
<br/>	 */
<br/>	public static boolean writeTextFile(String name, String[] lines) {
<br/>		boolean success = true;
<br/>		PrintWriter pw = null;
<br/>		try {
<br/>			FileWriter fw = new FileWriter(name); // create a new file
<br/>			pw = new PrintWriter(fw); // wrap a convenient stream for writing lines
<br/>			for (int i = 0; i < lines.length; i++) {
<br/>				pw.println(lines[i]); // write line by line into the file
<br/>			}
<br/>			// flush OS buffers, otherwise OS can wait till the buffers are full
<br/>			// before writing to a file
<br/>		} catch (IOException e) {
<br/>			success = false;
<br/>		} finally {
<br/>			pw.flush();
<br/>			pw.close();
<br/>		}
<br/>		return success;
<br/>	}
<br/>
<br/>

In this example we again use the finally block to close the writing stream in any case: with normal or abnormal operation.
Assignments:
1. Read the Exceptions tutorial from Oracle.
2. Open Eclipse and in the project week2 create another package day8. Copy or (better) re-type the IOMaster source to this package. Then modify all methods to handle exceptions as in the examples above. Do not forget to modify the main method and check the results.
3. Open Windows Explorer and navigate to the c:/its-resources folder. Create in this folder another text file with the WordPad, type several lines, and save as day8.txt.
Create another new class TestReadText.
In this class create the main method and in the main method call the utility IOMaster.readTextFile with the argument "c:/its-resources/day8.txt".
The utility will return the text that you typed in this file manually.

Your line in the main method will look like this:
String text = IOMaster.readTextFile("c:/its-resources/day8.txt");

Then add the line to display the text.

When finished, run the main method: Right mouse click on the source ? Run As ? Java Application.
Check the results in the console.
4. In a similar way create and run the following classes: TestWriteText, TestWriteBin, and TestReadBin
Topic Graph | Check Your Progress | Propose QnA | Have a question or comments for open discussion?

Have a suggestion? - shoot an email
Looking for something special? - Talk to me
Read: IT of the future: AI and Semantic Cloud Architecture | Fixing Education
Do you want to move from theory to practice and become a magician? Learn and work with us at Internet Technology University (ITU) - JavaSchool.com.

Technology that we offer and How this works: English | Spanish | Russian | French

Internet Technology University | JavaSchool.com | Copyrights © Since 1997 | All Rights Reserved
Patents: US10956676, US7032006, US7774751, US7966093, US8051026, US8863234
Including conversational semantic decision support systems (CSDS) and bringing us closer to The message from 2040
Privacy Policy