Throws keyword and Constructors

 

Definitely, we can use throws keyword with constructors because constructors may have many numbers of statements which are proven to generate exception class objects.

 

Class Edemo4

{

Int    I, j, k;

Edemo4 (int x, int y) throws Exception

{

I=x; j=y;

K – i/j;

}

}

Class Test4

{

Public static void main (string args [ ])

{

Try

{

Edemo4 e1 = new Edemo4 (10, 0);

}

Catch (Exception e1)

{

System .out. println (e1);

}

System .out. println (e1 . i); \\ compilation error

}

}

  •  Error occurs because, e1 is defined inside the try block and hence it is local to try System .out. println (e1 . i) is outside try and is again proven to generate checked exceptions.
  • To avoid this problem, define e1 outside the try block and inside the main () so that it will be available to all other parts of main (), as shown below.

 

Example:

Class Test4

{

Public static void main (string args [ ])

{

Edemo4 e1 = null;

Try

{

e1 = new Edemo4 (10, 0);

}

Catch (Exception e)

{

System .out. println (e);

}

System .out. println (e1 . i); \\ now we do not have any compilation error

}

}

 

Point to remember regarding try- catch:

  • Whenever try block has n number of blocks, then if an exception object is created, the order of preference of catch blocks is, the order in which they are present below the try block.

Consider the following scenarios:

Try

{

====

}

Catch (Arithmetic Exception e1)

{

System .out. println (e1);

}

Un reached blocks

Catch (null point Exception e2)

{

System .out. println (e2);

}

Catch (exceptions e)

{

System .out. println (e);

}

Now, if at all an exception is raised in a try block, it will be transferred to the immediate catch block. If that catch block is not capable of handling that exception, then it is transferred to the next catch block and so on.

 

Throws keyword and Constructors Homework Help