An exception is a problem that arises during the execution of a program. There might be many reason for an exception. Some exception might occur due to invalid data entered by user or some network issue.
- A user has entered invalid data.
- A file not found
- A network connection has been lost
To understand how exception handling works in Java, you need to understand the three categories of exceptions:
Checked exceptions: A checked exception is an exception that is typically a user error or a problem that cannot be foreseen by the programmer. For example, if a file is to be opened, but the file cannot be found, an exception occurs. These exceptions cannot simply be ignored at the time of compilation so they are called checked exceptions.
Runtime exceptions: A runtime exception is an exception that occurs that probably could have been avoided by the programmer. As opposed to checked exceptions, runtime exceptions are ignored at the time of compliation so they are called as unchecked exceptions.
Errors: These are not exceptions at all, but problems that arise beyond the control of the user or the programmer. Errors are typically ignored in your code because you can rarely do anything about an error. For example, if a stack overflow occurs, an error will arise. They are also ignored at the time of compilation.
Exception Hierarchy:
Errors are not normally trapped form the Java programs. These conditions normally happen in case of severe failures, which are not handled by the java programs. Errors are generated to indicate errors generated by the runtime environment. Example : JVM is out of Memory. Normally programs cannot recover from errors. You need take Exception most seriously as this will encounter you all the ways in exception handling.
The Exception class has two main subclasses : IOException class and RuntimeException Class. All the IOExceptions(includind child exception) are checked exceptions while all the RuntimeException are unchecked exceptions.
Method in Exception:
There are many method available in Exception class but most of the time you use only following three methods,
public String getMessage()
public void printStackTrace()
public Throwable getCause()
Exceptional Handling Coding:
We have talked a lot about theoretical part of Exceptions. Now its time to play with coding. As you might be knowing, exception handling is dong using try, catch and finally block. out of these, try and one catch is essential as you can have multiple catch. finally is option and comes after last catch block. Code those are likely to throw exception are placed in try block and if exception occurs at any line, execution is break from that point and jumped to appropriate catch block. Once it finish execution of catch block, program execution jumps to finally block, if any and continue execution after that.
finally block is called in all the cases whether exception is occurred or not while corresponding catch executes only if exception of its kind occurs. If there is some return before finally, even then program will execute finally block and then returns.
Sample structure of exception handling will be,
************************************************************
try {
//code that throw exception
}
catch(ExceptionType1 et1){}
catch(ExceptionType2 et2){}
catch(ExceptionType3 et3){}
finally {}
************************************************************
Method in Exception:
There are many method available in Exception class but most of the time you use only following three methods,
public String getMessage()
public void printStackTrace()
public Throwable getCause()
Exceptional Handling Coding:
We have talked a lot about theoretical part of Exceptions. Now its time to play with coding. As you might be knowing, exception handling is dong using try, catch and finally block. out of these, try and one catch is essential as you can have multiple catch. finally is option and comes after last catch block. Code those are likely to throw exception are placed in try block and if exception occurs at any line, execution is break from that point and jumped to appropriate catch block. Once it finish execution of catch block, program execution jumps to finally block, if any and continue execution after that.
finally block is called in all the cases whether exception is occurred or not while corresponding catch executes only if exception of its kind occurs. If there is some return before finally, even then program will execute finally block and then returns.
Sample structure of exception handling will be,
************************************************************
try {
//code that throw exception
}
catch(ExceptionType1 et1){}
catch(ExceptionType2 et2){}
catch(ExceptionType3 et3){}
finally {}
************************************************************
Remember, In case of multiple catch, a superclass exception can not come before child class exception i.e. if there are child and parent exception in catch block, child will be handled first then its parent.
************************************************************
class JDBCConnection {
public static void main (String args[]) throws SQLException
{
Connection conn = null;
Statement stmt = null;
try {
Class.forName ("oracle.jdbc.driver.OracleDriver");
conn=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "scott", "tiger");
// host:port:SID, username, password
stmt = conn.createStatement();
ResultSet rset = stmt.executeQuery("select * from tblEmployee");
while (rset.next())
{
System.out.println (rset.getString(1)); // empName
System.out.println (rset.getInt(2)); // empCode
System.out.println (rset.getInt(3)); // empSalary
System.out.println (rset.getString(4)); // empAddress
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch(SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
} finally {
conn.close();
stmt.close();
}
}
}
************************************************************
By reading the above cod, you will get an idea of exception handling in Java. Just remember, any code that might throw an exception will come under try bock while all the exception thrown by codes are handled in catch block. You can have any number of catch block depending number of exceptions. Now we will discuss about throwing an exception manually.
Throw an Exception:
An exception can be thrown at any point of time in a program using throw keyword. You just need to create an object of Exception and throw it using throw keyword. any method that throw exception need to declared it in its signature using throws keyword. Just look at code blow,
************************************************************
package com.codinguide.struts.util;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class FileReader {
/**
* read file
* @param fileName
* @throws IllegalArgumentException
* @throws FileNotFoundException
*/
public void readFile(String fileName) throws IllegalArgumentException, FileNotFoundException {
if ( null == fileName ){
throw new IllegalArgumentException("File name is null");
}
byte b[] = new byte[1024];
FileInputStream fis = new FileInputStream(fileName);
try {
while (-1 != fis.read(b));
System.out.println(new String(b));
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
FileReader fr = new FileReader();
try {
fr.readFile("D://example1.log");
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
************************************************************
You might have notices following points,
You can create your exception. In fact mostly you need to create custom Exceptions for your application. This is much easier then it sounds. Just look at code blow
*************************************************************
package com.codinguide.exceptions;
public class CodinguideException extends Exception{
public CodinguideException(Throwable exp){
super(exp);
}
public CodinguideException(String message){
super(message);
}
}
*************************************************************
Here is your custom exception. This is base exception. You can create specific exception like CodingGuideFileMissingException by sub classing FileNotFound exception and use its in place of default exceptions.
By reading the above cod, you will get an idea of exception handling in Java. Just remember, any code that might throw an exception will come under try bock while all the exception thrown by codes are handled in catch block. You can have any number of catch block depending number of exceptions. Now we will discuss about throwing an exception manually.
Throw an Exception:
An exception can be thrown at any point of time in a program using throw keyword. You just need to create an object of Exception and throw it using throw keyword. any method that throw exception need to declared it in its signature using throws keyword. Just look at code blow,
************************************************************
package com.codinguide.struts.util;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class FileReader {
/**
* read file
* @param fileName
* @throws IllegalArgumentException
* @throws FileNotFoundException
*/
public void readFile(String fileName) throws IllegalArgumentException, FileNotFoundException {
if ( null == fileName ){
throw new IllegalArgumentException("File name is null");
}
byte b[] = new byte[1024];
FileInputStream fis = new FileInputStream(fileName);
try {
while (-1 != fis.read(b));
System.out.println(new String(b));
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
FileReader fr = new FileReader();
try {
fr.readFile("D://example1.log");
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
************************************************************
You might have notices following points,
- We don't need to handle all the exception. We can simply throw them.
- All the thrown exception must be declared in method signature using throws keyword.
- We can use both try/catch and throw/throws in same method.
- All the thrown exception must be handled by calling method. You can ignore unchecked exception but its better to handled them too.
Now here is point, whether you need to use throw/throws or try catch. If your method encounter encounter some problem due to external reason like file name is null or file not found then you need to notify calling method about it as its not method fault so throw the exception. If problem is due to method processing like IOException then you need to handle this within the method hence use try catch.
Depending upon the way exception are thrown, can have two categories:
JVM Exceptions: These are exceptions/errors that are exclusively or logically thrown by the JVM, like NullPointerException, ArrayIndexOutOfBoundsException, ClassCastException, FileNotFoundException.
Programmatic Exceptions: These exceptions are thrown explicitly by the application or the API programmers like IllegalArgumentException, IllegalStateException.
Create Your Exception:Depending upon the way exception are thrown, can have two categories:
JVM Exceptions: These are exceptions/errors that are exclusively or logically thrown by the JVM, like NullPointerException, ArrayIndexOutOfBoundsException, ClassCastException, FileNotFoundException.
Programmatic Exceptions: These exceptions are thrown explicitly by the application or the API programmers like IllegalArgumentException, IllegalStateException.
You can create your exception. In fact mostly you need to create custom Exceptions for your application. This is much easier then it sounds. Just look at code blow
*************************************************************
package com.codinguide.exceptions;
public class CodinguideException extends Exception{
public CodinguideException(Throwable exp){
super(exp);
}
public CodinguideException(String message){
super(message);
}
}
*************************************************************
Here is your custom exception. This is base exception. You can create specific exception like CodingGuideFileMissingException by sub classing FileNotFound exception and use its in place of default exceptions.
1 comment:
Pretty nice post. I just stumbled upon your blog and wanted to say that I have really enjoyed browsing your blog posts. In any case I’ll be subscribing to your feed and I hope you write again soon!
Post a Comment