User Defined Exceptions using Constructors in Java Last Updated : 28 Jan, 2021 Summarize Comments Improve Suggest changes Share Like Article Like Report In Java, we have already defined, exception classes such as ArithmeticException, NullPointerException etc. These exceptions are already set to trigger on pre-defined conditions such as when you divide a number by zero it triggers ArithmeticException. In Java, we can create our own exception class and throw that exception using throw keyword. These exceptions are known as user-defined or custom exceptions. Problem statement: Realize a Java class Matrix to represent bi-dimensional matrices of real numbers. The class should export the following methods: Matrix(int n, int m): Constructor that creates a matrix of size nxm, with all values initially set to 0; Matrix product(Matrix m): It returns the matrix that is the product of the object and of m, if the two matrices have compatible dimensions, and null otherwise; ExceptionWrongMatrixDimension that is thrown in the method check() if the dimension of the matrix is wrong for the multiplication of the matrix. Example: Java // Java program to create user defined // exceptions import java.util.Scanner; // User defined exception class to store the exception // message class ExceptionWrongMatrixDimension extends Exception { public ExceptionWrongMatrixDimension(String str) { // stores the exception message to be displayed super(str); } } class twoDimensionalMatrix { void Matrix(int n, int m) throws ExceptionWrongMatrixDimension { // initialize matrix to be processed int[][] matrix = { { 1, 2 }, { 4, 5, } }; System.out.println("\nMatrix is :"); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { System.out.print(matrix[i][j] + " "); } System.out.println(); } int rows = 2; int cols = 2; if (n != rows) { // throw keyword for an exception in a method throw new ExceptionWrongMatrixDimension( "Invalid matrix dimensions to multiply"); } else { int[][] m_matrix = { { 6, 3 }, { 9, 2, } }; System.out.println("\nMatrix to multiply is :"); for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { System.out.print(m_matrix[i][j] + " "); } System.out.println(); } System.out.println("\nMatrix to multiply is :"); for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { System.out.print(m_matrix[i][j] + " "); } System.out.println(); } int c[][] = new int[m][n]; for (int i = 0; i < rows; i++) { for (int j = 0; j < rows; j++) { c[i][j] = 0; for (int k = 0; k < rows; k++) { c[i][j] += matrix[i][j] * m_matrix[k][j]; } } } System.out.println( "\n\nMatrix after multiplication is"); for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { // prints the third matrix containing // the multiplied values System.out.print(c[i][j] + " "); } System.out.println(); } } } } public class Main { public static void main(String args[]) { twoDimensionalMatrix matrix = new twoDimensionalMatrix(); try { // block of code to be tested for errors while // it is being executed. System.out.println("Enter the number of rows"); int n = 2; System.out.println( "Enter the number of columns"); int m = 2; matrix.Matrix(n, m); } catch (ExceptionWrongMatrixDimension e) { // block of code to be executed, if an error // occurs in the try block. System.out.println( "ExceptionWrongMatrixDimension:"); // returns a method object. The name parameter // is passed as a string. System.out.println(e.getMessage()); } } } OutputEnter the number of rows Enter the number of columns Matrix is : 1 2 4 5 Matrix to multiply is : 6 3 9 2 Matrix to multiply is : 6 3 9 2 Matrix after multiplication is 15 10 60 25 Comment More infoAdvertise with us Next Article ClosedChannelException in Java with Examples S snehaveerakumar Follow Improve Article Tags : Java Technical Scripter Java Programs Java-Exceptions Java-Constructors Java 8 +2 More Practice Tags : Java Similar Reads How to Solve IllegalArgumentException in Java? An unexpected event occurring during the program execution is called an Exception. This can be caused due to several factors like invalid user input, network failure, memory limitations, trying to open a file that does not exist, etc. If an exception occurs, an Exception object is generated, contai 3 min read ClosedChannelException in Java with Examples The class ClosedChannelException is invoked when an I/O operation is attempted on a closed channel or a channel that is closed to the attempted operation. That is if this exception is thrown, however, does not imply the channel is completely closed but is closed to the attempted operation. Syntax: p 4 min read Using throw, catch and instanceof to handle Exceptions in Java Prerequisite : Try-Catch Block in Java In Java, it is possible that your program may encounter exceptions, for which the language provides try-catch statements to handle them. However, there is a possibility that the piece of code enclosed inside the 'try' block may be vulnerable to more than one ex 4 min read Java Program to Handle Checked Exception Checked exceptions are the subclass of the Exception class. These types of exceptions need to be handled during the compile time of the program. These exceptions can be handled by the try-catch block or by using throws keyword otherwise the program will give a compilation error.  ClassNotFoundExcept 5 min read java.io.FileNotFoundException in Java java.io.FileNotFoundException which is a common exception which occurs while we try to access a file. FileNotFoundExcetion is thrown by constructors RandomAccessFile, FileInputStream, and FileOutputStream. FileNotFoundException occurs at runtime so it is a checked exception, we can handle this excep 4 min read How to Handle an IOException in Java? An IOException in Java occurs when we try to perform some input or output tasks and then some issues occur. Programmers need to handle this issue explicitly with a piece of code that executes when an issue occurs. There is an entire class for handling such issues known as the IOException class, whic 3 min read Like