Some years ago I found myself at dinner with a handful of judges – a bench is the collective noun. They were talking shop, and I was politely resisting the urge to take notes. The conversation was exotic in content, rather familiar in form. There was a fair amount of banter, of chuckling and teasing as they recalled certain of each other's judgments. They quoted well-turned phrases and fondly remembered ingenious conclusions. Clearly, they read each other closely. They may have been a little harder on the judgments of those not present. How easily, I thought at the time, this bench could be mistaken for a group of novelists discussing each other's work, reserving harsher strictures for those foolish enough to be absent.

At one point, our host, Sir Alan Ward, an appeal court judge, wanting to settle some mild disagreement, got up and reached from a shelf a bound volume of his own judgments. An hour later, when we had left the table for coffee, that book lay open on my lap. It was the prose that struck me first. Clean, precise, delicious. Serious, of course, compassionate at points, but lurking within its intelligence was something like humour, or wit, derived perhaps from its godly distance, which in turn reminded me of a novelist's omniscience. I continued to note the parallels between our professions, for these judgments were like short stories, or novellas; the background to some dispute or dilemma crisply summarised, characters drawn with quick strokes, the story distributed across several points of view and, towards its end, some sympathy extended towards those whom, ultimately, the narrative would not favour.

These were not cases in the criminal courts, where it must be decided beyond reasonable doubt whether a man is a villain or the unlucky victim of the Crown Prosecution Service. Nothing so black and white, nothing so noir or pulp. These stories were in the family division, where much of ordinary life's serious interests lie: love and marriage, and then the end of both, fortunes querulously divided, the bitterly contested destinies of children, parental cruelty and neglect, deathbed issues, medicine and disease, religious or moral disputes complicating matrimonial breakdown.

The choices for a judge are often limited to the lesser harm rather than the greater good. When mother and father cannot agree, the court reluctantly assumes the role of the "judicial reasonable parent". Here, in my lap, were realistically conceived characters moving through plausible, riveting situations, raising complex ethical questions. If these judgments had been fiction, they would have belonged in the tradition of moral exploration that includes Jane Austen, Leo Tolstoy, George Eliot, Henry James, Joseph Conrad.

Then I came across an arresting sentence. It was in the opening paragraphs of a judgment in the court of appeal in 2000 concerning baby conjoined twins. Untreated, both would die. Separated, the weaker must perish, for it had a failing heart, virtually no brain and "no lungs to cry with". Only its healthier sibling kept it alive by way of their shared circulatory system. And slowly, the weak baby was sapping the strength of the strong. The hospital wanted to operate to save the viable child, but surgery would involve deliberately killing its twin by severing an aorta. The parents objected for religious reasons: God gave life; only God could take it away. Public interest was intense.

On the face of it, a simple moral premise: one rescued and flourishing child is better than two dead. But how was the law to sanction murder, and set aside the insistence of the parents, endorsed by the then Roman Catholic Archbishop of Westminster, that both children should be left to die?

Appeal court judge Sir Alan Ward. Photograph: Johnny Green/PA

In his introductory remarks Ward had offered a reminder to the general public: "This court is a court of law, not of morals, and our task has been to find, and our duty is then to apply, the relevant principles of law to the situation before us – a situation which is unique."

What is lawful is not always identical to what is right. Sometimes it falls to a judge to align the two. Ward's judgment runs to more than 80 closely typed pages. It is beautifully written, delicate and humane, philosophically astute, ethically sensitive and scholarly, with a wide range of historical and legal references.

The best of judgments, as I was to discover, are similarly endowed. They form a neglected subgenre of our literature, read in their entirety by almost no one except law students – and fellow judges. And in the family division particularly, they present a hoard of personal drama and moral complexity. They are on fiction's terrain, even though they are bound, unlike the fortunate novelist, to a world of real people and must deliver a verdict.

But as we all know, verdicts, indeed the whole system, can also be asinine – tough, even tragic, for its innocent victims, grimly fascinating for the novelist. For the obvious is true, the law is human and flawed. Just like newspapers or medicine or the internet, it embodies all that is brilliant and awful about humankind.

One of the sorriest and most sustained judicial errors in modern times was in the case of Sally Clark, the solicitor, two of whose children died of cot death. She was charged with their murder. The jury appeared impressed by some breathtaking statistical nonsense from one medical witness. Various other experts disagreed with each other profoundly about the causes of death, but the court showed no appropriate caution and she was found guilty. The tabloids "monstered" her, in jail she was horribly bullied, her appeal was turned down. By her second appeal it was apparent that a pathologist had withheld vital evidence about a fatal bacterial infection in one of Clark's children and finally she was released. But by then a few years had passed and the ordeal had broken her. A bereaved mother, brave and decent, harried by the legal system like a figure in a Kafka story, persecuted like Job, she lost her life to depression and drink.

Solicitor Sally Clark with her husband outside the high court. She was freed after her conviction for the murder of her two baby sons was ruled unsafe by the court of appeal. Photograph: Dan Chung for the Guardian

The Guildford Four and Maguire Seven, the Birmingham Six … a brief search on the internet will show that the list of less famous victims of miscarriages of justice in the courts is vast. And these are only the cases that have been successfully appealed. Then there are those that attract baffling lenience: a cyclist who rode extremely fast on the pavement and killed a 17-year-old pedestrian was ordered to pay a fine, and avoided jail. Or the punishment is weirdly harsh: a young man of my close acquaintance was caught by CCTV cameras on the edge of a pub brawl. He hurt no one, though he did manage to receive a split lip. On a "joint enterprise" basis, he was punished for offences committed by others, and for which the police hadn't even charged him. He is currently serving a two and half year sentence. And he was lucky – the prosecution was pushing for five to nine years. When I showed the case to a recently retired and very senior member of the judiciary, he was dismissive: "Not even worth a suspended sentence."

My young friend was often locked in his cell 23 hours a day in the Isis prison at Thamesmead, an institution that boasts "a broad-based curriculum that supports academic achievement, vocational training" etc. He lost his freedom for the grievous bodily harm the court accepted he did not inflict. Other mitigating factors, including previous wrongful imprisonment, were not addressed in the summing up. Had he been listed to appear before another judge, he might be enjoying the company of his partner and their baby, who was born just before he was sent down. As Kurt Vonnegut might have murmured as my friend was led away, so it goes.

Despite sentencing guidelines, there can be no consistency in the courts, unless everyone stands before the same even-tempered judge, as at the Day of Judgment. Perhaps this was always part of Christianity's appeal. Until that last trump, down here in the earthly courts brilliance and fairness must live alongside dull injustice. In the criminal courts neither jury nor judge are permitted to conclude that something might have happened. It either did or did not. Mistakes therefore are wired into the system. In the family division judges often make moral choices. Lord Hoffmann put the best face on it when he wrote, "These are value judgments on which reasonable people may differ. Since judges are also people, this means that some degree of diversity in their application of values is inevitable."

It follows that the judge and his or her character, moral sense, background, mood swings and attention span (one judge was recently reported to have fallen asleep while hearing evidence) have great consequence for the destinies of those who come before them. But the vast and rich fiction that has grown up around the law has been mostly fascinated by criminals and their victims, and the criminals' antagonists in the form of cops, private eyes and attorneys. Crime fiction as a genre has such sustained and wide popularity that it has become, inevitably, sclerotic with conventions. Fictional crime victims (of rape, of murder) are most often very beautiful young women. The investigating cop is expected to have a deeply flawed character and a disastrous private life. One follows less often, in fiction or on TV, the happily married detective of steady temperament pursuing the killer of a fat old geezer with bad breath.

Judges have not entirely escaped fictional invention. Apart from God himself and Judge Dredd (both so careless of due process) one eminent figure is Lewis Carroll's Queen of Hearts, whose multiple sentences of instant beheading are quietly reversed by her husband, the king, though he becomes less lenient and far more erratic as judge at the trial of the Knave of Hearts. As John Mortimer's Rumpole famously noted, a court is a blunt instrument to get at the truth.

Just as religion and religious passion and disputes have pervaded domestic and international politics to an extent we could not have predicted 20 years ago, so they have vigorously entered, or re-entered, the private realm, and therefore the family courts. In the case of the conjoined twins, Ward ruled against the parents and for the hospital. But it was, as the nice legal term has it, "an anxious question". The operation went ahead, the weaker baby died (or, as the then Archbishop of Westminster might have put it, was judicially murdered), while its sibling underwent extensive reconstructive surgery and flourished.

This was a high-profile case. Elsewhere, the family law reports are littered with routine disputes over the religious upbringing of children. Divorcing parents find themselves with irreconcilable differences over which "truth" their children are to be raised in. A Jehovah's Witness mother, opposed to Christmas celebrations because of their pagan origins, withdraws her child from the school nativity play on religious grounds. Her estranged Anglican husband objects. A Saudi father wants to remove his daughter from the jurisdiction to his homeland, where she will be brought up in his Muslim faith. The mother, a Catholic, brings a court action – but too late. An orthodox Hasidic father wants his children raised within his close community, without access to TV, the internet, pop music and fashion, and to leave school at 16. His less devout Jewish ex-wife will fight him to the end for the souls of their children.

Complex issue of religious freedom and child welfare bring these cases to the high court and beyond, to the court of appeal. Reluctantly, at a snail's pace, the law gets involved in the minutiae of daily arrangements – the sort of arrangements that couples in love could settle in seconds. Judgments in the family division tend to genuflect politely before the religious devotion of the parties, before arriving at decisions on non-religious grounds. Inevitably, there are differences in moral perspectives. Is this life less important than the afterlife? The law doesn't think so. Does God abhor homosexuality and abortion? Parliament has decided these issues and the courts must fulfil its will. Is it right to punish those who reject their own religion? The criminal courts must punish the punishers.

After a judge has heard out the warring parties and comes to settle the destinies of the children, the guiding principle will be the opening lines of the Children Act, 1989. "When a court determines any question with respect to … the upbringing of a child … the child's welfare shall be the court's paramount consideration." If this sounds like a tautology, it's a useful one; the needs and interests of the parents or their gods are secondary to the interests of the child. If the act raises the question of what a definition of welfare should be, then a judge ought to be able to provide one in the role of "judicial reasonable parent".

Three years after my supper with that bench of judges, Ward told me of a Jehovah's Witness case he had once presided over. At the time he was doing his turn as duty judge, ready at the end of a phone, nights and weekends, to deal with emergency applications to the court. One came late in the evening from a hospital looking for permission to transfuse a Jehovah's Witness teenager against his and his parents' wishes. The boy was suffering from a form of leukaemia that was relatively easy to cure. The drugs the doctors wanted to use would compromise his already declining blood count. The medical staff were fiercely opposed to losing a patient they thought they could cure. The matter was urgent. Within a short time, the various parties, their representatives and expert witnesses assembled in the Royal Courts of Justice to present evidence and argument to the judge.

The Royal Courts of Justice in London, which houses the court of appeal. Photograph: Graham Turner for the Guardian

A considerable distance in worldviews between secular law and supernatural belief is exposed in cases involving Jehovah's Witnesses and blood transfusion, especially where a child is concerned. And in this context, a child is anyone under 18. In law, the closer he gets to that age, the more his wishes have to be taken into account. Here is another anxious question. To refuse medical treatment for oneself is understood in law to be a fundamental right. A doctor who treats a patient against his will is committing criminal assault.

For Jehovah's Witnesses, the matter is simpler, though fraught with sacrifice and pain. The Bible is the word of God. His interdictions against blood transfusion are set out in Genesis, Leviticus and Acts. If the religion's Governing Body in Brooklyn ("the slaves") did not advise the worldwide followers ("the other sheep") against transfusion until 1945, it's because God prefers to reveal his wishes gradually and obliquely. As one Witness pointed out recently on my doorstep, the truth about blood was always waiting to be discovered. To the glib assertion that transfusion was not a feature of iron age therapies, any other sheep will be able to cite one of the relevant verses: "Only flesh with its life, its blood, you must not eat." (Genesis 9:4). Pointless, it turns out, arguing over the verb.

In the case of the five-year-old Ashya King, the knowledge that his parents were Jehovah's Witnesses may just possibly have prompted the confused, overheated responses of the Southampton hospital and police, and the CPS. The religion does not forbid its members sophisticated medical treatment and, as far as we know, in this sad and tangled affair blood transfusion is not at issue.

Brett and Naghmeh King, parents of five year old Ashya King, hold a press conference in Seville, Spain. Photograph: Denis Doyle/Getty Images

But when it is, the matter often comes before a judge as a matter of life and death. Hospitals need a rapid decision. Even if the "child" is within a week of his 18th birthday, has his parents' backing, clearly knows his own mind and would rather die than be transfused, the act directs the court to the only proper decision. The paramount consideration is clear: no child's welfare is served by being martyred for his religion.

Many hospitals have devised elaborate means to accommodate the faithful with "bloodless surgery". Some Witnesses are prepared to trim by accepting their own recycled blood or certain blood products. But tragedies occur. The law exists to set and live by boundaries. One moment past its 18th birthday, the child is no more and is beyond the court's protection.

To embrace death, or allow one's child to die, for a questionable reading of certain biblical dietary restrictions will seem to most a pointless pursuit of grief. To die for one's beliefs is not always noble, and sincerity is not necessarily a virtue. For an extreme example, recall the 9/11 attackers, and all the gullible, murderous suicide bombers that followed. Most of us, even Christians, now struggle to understand those 16th-century martyrs who chose to be burned at the stake rather than yield on finer points of Protestant or Catholic dogma.

We prefer to think we are remote and well defended from such sacrifice. But there are always exceptions we might make, as long as we are brave enough. Some scales of moral value, some sacrifices, are superior, more meaningful, than others. We honour the parent who drowns while rescuing a child, as we do the men and women who gave their lives liberating Europe from Nazi barbarity. That in turn summons the complicating memory of the many Jehovah's Witnesses who were rounded up in the Third Reich's death camps and offered their freedom if they would renounce their pacifism. They always chose to die.

Back in the days when Ward was hearing his blood transfusion case, it was still possible for him to make a minor a ward of court. At some point in the proceedings he decided to go and meet his ward in person – a clear instance of the personality of the judge determining the course of a case. He suspended proceedings, crossed London in a taxi, met the loving, anxious parents, then sat at the boy's hospital bedside for an hour. Among many other things, they talked about football, which was the lad's passion. Later that evening, the judge returned to the Courts of Justice to give his decision. He "set aside" his ward's and the parents' articulately expressed refusal of a blood transfusion and ruled for the hospital. The child's welfare was his paramount consideration.

Some Jehovah's Witnesses are prepared to accept certain blood products. Photograph: Martin Argles for the Guardian

Months later, Ward took the boy (now in good health) and his father to a football match, which they watched from the directors' box. The young man was able to meet his football heroes. The gleam of joy in his eyes, his excitement at being alive, was a sight the judge would never forget. The court's decision was vindicated. But the story did not end there. A few years later the young Witness was readmitted to hospital and needed another blood transfusion. By then, he was old enough to make an independent decision. He refused treatment and died for his beliefs.

Contemplating this tragedy one can only guess at the sorrow, the parents' thwarted love, the powerful sense of destiny they shared with their son, and all the defeated arguments of the court, the desolation of the nursing staff – and the waste. The character of the judge, who was so compassionately and rationally intent on a good outcome, seemed inseparable from the story. When I heard it, I remembered my earlier impression – the family division is rooted in the same ground as fiction, where all of life's vital interests lie. With the luxury of withholding judgment, a novel could interpose itself here, reinvent the characters and circumstances, and begin to investigate an encounter between love and belief, between the secular spirit of the law and sincerely held faith.

 Podcast: Ian McEwan on The Children Act

 Video: Ian McEwan on religion in the 21st century

 Video: Ian McEwan on Ashya King

• The Children Act by Ian McEwan is published by Jonathan Cape. To order a copy for £13.59 with free UK p&p call Guardian book service on 0330 333 6846 or go to guardianbookshop.co.uk.