How to use exception handling in Java:
We have seen how to use a try-catch statement to identify program code that may cause an exception and how to deal with particular exceptions that may arise. There are some additional issues about how best to use this facility.
Firstly, it is best to be as specific as possible about the type of exception you expect to be generated. For example, it is usually a bad idea to do this:
try
{
// code that may throw various exceptions
}
catch (Exception ex)
{
// code that handles any exception
}
Using specific types of exception in the catch clauses has advantages. It documents the types of exception expected and also allows the exception handlers to deal more specifically with each type of exception.
Secondly, you do not have to deal with every possible type of exception. Any exception that cannot usefully be dealt with inside a particular method can be passed on to a higher level. This is another reason to be specific about the types of exception in the catch clauses.
It is possible and sometimes helpful to have more than one try statement within a method. This clearly defines the area of code where each exception is expected to arise:
try
{
// code that may throw a FileNotFoundException
}
catch (FileNotFoundException ex)
{
}
//
// code that handles a FileNotFoundException
// other code
//
try
{
// code that may throw an EOFException
}
catch (EOFException ex)
{
// code that handles an EOFException
}
There is clearly a balance to be struck here. Having one, possibly rather large try block may make it hard to identify which type of exception occurs where. It may also encourage the undesirable 'one size fits all' style of exception handling that we saw at the start of this subsection. On the other hand, having too many separate try blocks may clutter up the rest of the code and make it less readable. The choice is a matter of professional judgement.
Java Assignment Help - Java Homework Help
Struggling with java programming language? Are you not finding solution for your How to use exception handling in Java homework and assignments? Live How to use exception handling in Java experts are working for students by solving their doubts & questions during their course studies and training program. We at Expertsmind.com offer How to use exception handling in Java homework help, java assignment help and How to use exception handling in Java projects help anytime from anywhere for 24x7 hours. Computer science programming assignments help making life easy for students.
Why Expertsmind for assignment help
- Higher degree holder and experienced experts network
- Punctuality and responsibility of work
- Quality solution with 100% plagiarism free answers
- Time on Delivery
- Privacy of information and details
- Excellence in solving java programming language queries in excels and word format.
- Best tutoring assistance 24x7 hours