Handling Exceptions in Generic Methods
This program demonstrates handling exceptions in generic methods.
Problem Statement
Write a Java program where generic method handles parsing exceptions.
Source Code
| 1 | public class GenericsExceptionExample { |
| 2 | public static <T> void parse(T input){ |
| 3 | try { |
| 4 | int num=Integer.parseInt(input.toString()); |
| 5 | System.out.println("Eduinq Parsed Number: "+num); |
| 6 | } catch(NumberFormatException e) { |
| 7 | System.out.println("Eduinq Exception: Invalid Format - "+input); |
| 8 | } |
| 9 | } |
| 10 | public static void main(String[] args) { |
| 11 | System.out.println("Eduinq Generics Exception Example"); |
| 12 | parse("123"); |
| 13 | parse("abc"); |
| 14 | } |
| 15 | } |
Program Output
Eduinq Generics Exception Example Eduinq Parsed Number: 123 Eduinq Exception: Invalid Format - abc
Explanation
Generic methods can handle exceptions for different input types. - Exception handling ensures safe parsing across varied inputs. - Improves flexibility and robustness. - In enterprise systems, generics exception handling ensures reusable utilities. Conclusion: Shows handling exceptions in generic methods.