
- Java Programming Examples
- Example - Home
- Example - Environment
- Example - Strings
- Example - Arrays
- Example - Date & Time
- Example - Methods
- Example - Files
- Example - Directories
- Example - Exceptions
- Example - Data Structure
- Example - Collections
- Example - Networking
- Example - Threading
- Example - Applets
- Example - Simple GUI
- Example - JDBC
- Example - Regular Exp
- Example - Apache PDF Box
- Example - Apache POI PPT
- Example - Apache POI Excel
- Example - Apache POI Word
- Example - OpenCV
- Example - Apache Tika
- Example - iText
- Java Tutorial
- Java - Tutorial
- Java Useful Resources
- Java - Quick Guide
- Java - Useful Resources
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java Examples - Exception with overloaded Methods
Problem Description
How to handle the exception with overloaded methods ?
Solution
This example shows how to handle the exception with overloaded methods. You need to have a try catch block in each method or where the are used.
public class Main { double method(int i) throws Exception { return i/0; } boolean method(boolean b) { return !b; } static double method(int x, double y) throws Exception { return x + y ; } static double method(double x, double y) { return x + y - 3; } public static void main(String[] args) { Main mn = new Main(); try { System.out.println(method(10, 20.0)); System.out.println(method(10.0, 20)); System.out.println(method(10.0, 20.0)); System.out.println(mn.method(10)); } catch (Exception ex) { System.out.println("exception occoure: "+ ex); } } }
Result
The above code sample will produce the following result.
30.0 27.0 27.0 exception occoure: java.lang.ArithmeticException: / by zero
The following is an another example to handle the exception with overloaded methods in Java
class NewClass1 { void msg()throws Exception{System.out.println("this is parent");} } public class NewClass extends NewClass1 { NewClass() { } void msg()throws ArithmeticException{System.out.println("This is child");} public static void main(String args[]) { NewClass1 n = new NewClass(); try { n.msg(); } catch(Exception e){} } }
The above code sample will produce the following result.
This is child
java_exceptions.htm
Advertisements